var COIN = 100000000;
var g_coin_obj = new BigNumber('0.00000001');
var TOKEN_LENGTH = 64;

var g_token   = (function() {
	var t = $.cookie('token');
	if (t && t.length == TOKEN_LENGTH) {
		return t;
	}
	return null;
})();
var g_user_id = $.cookie('user_id') ? $.cookie('user_id') * 1 : 0;
var g_user_info = null;
var g_last_show_chat_time = 0;
var g_chat_unread_count = 0;
var socket = io.connect('//' + config.websocket.host + ':' + config.websocket.port);

var	g_jplayer;  // audio player
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
}

var g_title_change = {old_title: '', timer: null, count: 0};

/* callback functions */
var g_callback = {
    '/site/info/': function(res) {
        parser.site_stat(res);
        g_bet_init_flag = (g_bet_init_flag | g_bet_init_flag_arr.site_info);
    	check_init();
    },
    '/user/info/': function(res) {
        parser.user_info(res);
        g_bet_init_flag = (g_bet_init_flag | g_bet_init_flag_arr.user_info);
    	check_init();
    },
    '/bet/listall/': function(res) {
    	if (res.hasOwnProperty('items') && res.items) {
    		parser.bet_listall(res.items.reverse());
    	}
    	g_bet_init_flag = (g_bet_init_flag | g_bet_init_flag_arr.bets_list);
    	check_init();
    },
    '/bet/listmine/': function(res) {
    	if (res.hasOwnProperty('items') && res.items) {
    		parser.bet_listmine(res.items.reverse());
    	}
    	g_bet_init_flag = (g_bet_init_flag | g_bet_init_flag_arr.bets_listmine);
    	check_init();
    },
    '/bet/broadcast/': function(res) {
    	if (res.hasOwnProperty('items') && res.items) {
    		parser.bet_listall(res.items);
    	}
    	if (res.hasOwnProperty('site_info') && res.site_info) {
    		parser.site_stat(res.site_info);
    	}
    },
    '/bet/do/': function (res) {
        if (res.hasOwnProperty('user_info')) {
        	parser.user_info(res.user_info);
        }
        if (res.hasOwnProperty('site_stat')) {
        	parser.site_stat(res.site_stat);
        }
        //console.log(res.bet);
        if (res.bet.referer*1 == 10001) {
        	/******    martigale    ******/
        	g_martingale.this_loop.bet_count += 1;
        	g_martingale.this_loop.profit    += res.bet.profit * 1.0 / COIN;
        	g_martingale.this_loop.last_bet_amount = res.bet.bet_amount * 1.0 / COIN;
        	g_martingale.this_loop.is_last_win = res.bet.is_win * 1;
        	$("#mtg_cur_profit").val(g_martingale.this_loop.profit.toFixedEx(8));
        	$("#mtg_bet_count").val(g_martingale.this_loop.bet_count);
        	// call again
        	if (g_martingale.interval_sec > 0) {
        		setTimeout(do_martingale, g_martingale.interval_sec * 1000);
        	} else {
        		if (res.bet.bet_amount*1 < 1000) {
    	        	// delay 1 seconds
    	        	setTimeout(do_martingale, 1000);
    	        } else {
    	        	setTimeout(do_martingale, 0);
    	        }
        	}
        	return;
        } else if (res.bet.referer*1 == 30000) {  
        	/******    simple    ******/
        	if (parseIntEx(res.bet.is_win) == 1) {
        		/** won **/
        		play_music_won();
        		
        		g_simple.profit = g_simple.profit.plus(res.bet.profit);
        		$("#simple_profit").val(g_simple.profit.dividedBy(COIN).toString().toFixedEx(8));
        		if (g_simple.profit.cmp(0) == 1) {
        			$("#btn_simple_take_it").removeClass('disabled');
        		}
        		// set new bet_amount
        		var new_start_bet_amount = g_simple.start_bet_amount.plus(g_simple.profit);
        		$('#simple_bet_amount').val(new_start_bet_amount.dividedBy(COIN).toString().toFixedEx(8));
        	} else {
        		/** loss **/
        		play_music_loss();
        		simple_take_it();
        	}
        	if (res.bet.bet_amount*1 < 1000) {
	        	// delay 1 seconds
	        	setTimeout(function() { unlock_bet(); }, 1000);
	        } else {
	        	unlock_bet();
	        }
        	return;
        } else {
        	/******    normal    ******/
        	if (parseIntEx(res.bet.is_win) == 1) {
        		play_music_won();
        	} else {
        		play_music_loss();
        	}
	         if (res.bet.bet_amount*1 < 1000) {
	        	// delay 1 seconds
	        	setTimeout(function() { unlock_bet();refresh_bet_options(); }, 1000);
	        	return;
	        }else {
	        	unlock_bet();
	        }
    	}
        refresh_bet_options();
    },
    '/chat/broadcast/': function (res) {
    	parser.chat_listall(res);
    },
    '/chat/listall/': function (res) {
    	if (res.hasOwnProperty('items') && res.items) {
    		parser.chat_listall(res.items.reverse());
    	}
    	g_bet_init_flag = (g_bet_init_flag | g_bet_init_flag_arr.chats_list);
    	check_init();
    	g_bet_init_flag_arr.chats_list = 0; // set zero, for unread counter
    },
    '/chat/new/': function(res) {
    	parser.chat_listall([res]);
    },
    '/jackpot/broadcast/': function(res) {
    	// for html title
    	g_title_change.timer && clearInterval(g_title_change.timer);
    	g_title_change.timer = setInterval(function () {
    		if (g_title_change.old_title.length == 0) {
    			g_title_change.old_title = document.title;
    		}
    		if (document.title == "Congratulations!") {
    			document.title = g_title_change.old_title;
    		} else {
    			document.title = "Congratulations!"
    		}
    		if (g_title_change.count++ >= 20) {
    			clearInterval(g_title_change.timer);
    			g_title_change.count = 0;
    			document.title = g_title_change.old_title;
    		}
    	}, 500);
    	
    	g_jplayer.jPlayer("setMedia", { mp3: "/audio/jackpot2.mp3"});
    	g_jplayer.jPlayer("play");
    	
    	var jackpot_pop = $("#jackpot_pop");
    	jackpot_pop.find('h4 span').html(res.user_name ? res.user_name : res.user_id);
    	jackpot_pop.find('p strong').html((res.amount / COIN).formatEx(8));
    	jackpot_pop.find('p a').attr("href", '/bet/detail/?bet_id=' + res.bet_id);
    	jackpot_pop.find('p a').html(res.bet_id);
    	
    	var msg = "user(id: " + res.user_id + ") got jackpot: " + (res.amount / COIN).toFixedEx(8) + " btc, bet id: " + res.bet_id;
    	jackpot_pop.fadeIn();
    	setTimeout(function () { $("#jackpot_pop").fadeOut(); }, 10000);
    },
    '/bet/newsrvseed/': function(res) {
    	$("#server_seed_hash").html(res.seed_hash);
    	$("#server_seed_id").val(res.bet_server_seed_id);
    	$("#loading").hide();
    }
};

/* parse data object to html page */
var parser = {
	/* user_info */
	user_info: function(user) {
		g_user_info = user;
		// show user vars
		var last_balance = get_balance() * COIN;  // get balance from page
		if (last_balance > user.btc_amount) {
			// loss
			$('#static .pull-left .span:first-child').addClass('down').removeClass('up');
		} else if (last_balance < user.btc_amount) {
			// win
			$('#static .pull-left .span:first-child').addClass('up').removeClass('down');
		}
		
		$("#user_btc_amount").html((user.btc_amount/COIN).formatEx(8));
		$("#user_stat_win_count").html(user.stat_win_count.formatEx());
		$("#user_stat_loss_count").html(user.stat_loss_count.formatEx());
		$("#user_stat_wagered").html((user.stat_wagered/COIN).formatExWithSmall(8));
	},
	
	/* site_stat */
	site_stat: function(site) {
		var site_wagered = $("#site_stat_wagered").html().replace(',', '').replace(/<[^>]*>/ig, '') * COIN;
		if (site_wagered >= site.site_stat_wagered) {
			return;
		}
		
		$("#site_max_bet_profit").html(parseInt(site.bankroll*config.bankroll.max_win_percent/COIN));
		$("#site_stat_wagered").html((site.site_stat_wagered/COIN).formatExWithSmall(8));
		$("#site_bankroll").html((site.bankroll/COIN).formatExWithSmall(8));
		$("#site_bet_count").html((site.site_stat_win_count * 1 + site.site_stat_loss_count * 1).formatEx());
		// jackpot
		var jackpot = new BigNumber(site.site_stat_wagered).minus(site.last_jackpot_site_wagered).times(config.jackpot.percent);
		if (jackpot.lessThan(config.jackpot.min_value)) {
			$("#site_jackpot_amount").addClass('muted');
		} else {
			$("#site_jackpot_amount").removeClass('muted');
		}
		$("#site_jackpot_amount span").html((jackpot.div(COIN)*1.0).formatExWithSmall(8));
	},
	
	// helper function: parse bet to html
	helper_bet2html: function(b) {
		var is_win = b.is_win == 1 ? true : false;
		var html = "<tr class=\"" + ($.cookie('user_id') == b.user_id ? ' me ' : '') + "\" >";
		// user_id
		html += "<td>" + b.user_id + "</td>";
		// bet time
		var t = new Date(b.bet_time_int * 1000);
		html += "<td>" + t.getFullYear() +'-' + (t.getMonth()+1).toZeroFillIntStr(2) + '-' + t.getDate().toZeroFillIntStr(2) + ' ';
		html += t.getHours().toZeroFillIntStr(2) + ':' + t.getMinutes().toZeroFillIntStr(2) + ':' + t.getSeconds().toZeroFillIntStr(2) + "</td>";
		// bet id, link
		html += "<td class=\"hidden-phone\"><a target=_blank href=\"/bet/detail/?bet_id=" + b.bet_id + "\">" + b.bet_id + "</a></td>";
		html += "<td>" + b.chance_to_win/10000 + "<small>%</small></td>";
		// lucky_number
		html += "<td><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">" + parseIntEx(b.lucky_number/10000) + '.';
		html +=  "<small>" + (b.lucky_number % 10000 / 10000).toFixedEx(4).substr(2, 4) + "</small></span></td>";
		// target
		html += "<td>" +(b.is_roll_high ? '&gt;' : '&lt;');
		var target_num = b.is_roll_high ? b.target_high : b.target_low;
		html += parseIntEx(target_num/10000) + '<small>.' + (target_num % 10000).toZeroFillIntStr(4) + "</small></td>";
		// payout_multiplier
		html += "<td>" + parseFloat(b.payout_multiplier).formatEx(8) + " x</td>";
		// bet_amount
		html += "<td class='hidden-phone'><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">";
		html += (is_win ? '+' : '-') + parseIntEx(Math.abs(b.bet_amount)/COIN) + '<small>.' + (b.bet_amount % COIN).toZeroFillIntStr(8) + "</small></span></td>";
		// profit
		html += "<td class='hidden-phone'><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">";
		html += (is_win ? '+' : '-') + parseIntEx(Math.abs(b.profit)/COIN) + '<small>.' + (b.profit % COIN * (is_win?1:-1)).toZeroFillIntStr(8) + "</small></span></td>";
		// referer
		html += "<td>" + get_referer(b.referer) + "</td>";
		html += "</tr>";
		return html;
	},
	
	// helper function: add to simple
	helper_add_to_simple_list: function(b) {
		// bet2html simple
		var is_win = b.is_win == 1 ? true : false;
		var html = "<tr class=\"" + ($.cookie('user_id') == b.user_id ? ' me ' : '') + "\" >";
		// bet time
		var t = new Date(b.bet_time_int * 1000);
		html += "<td>" + t.getFullYear() +'-' + (t.getMonth()+1).toZeroFillIntStr(2) + '-' + t.getDate().toZeroFillIntStr(2) + ' ';
		html += t.getHours().toZeroFillIntStr(2) + ':' + t.getMinutes().toZeroFillIntStr(2) + ':' + t.getSeconds().toZeroFillIntStr(2) + "</td>";
		// bet id, link
		html += "<td class=\"hidden-phone\"><a target=_blank href=\"/bet/detail/?bet_id=" + b.bet_id + "\">" + b.bet_id + "</a></td>";
		// payout_multiplier
		html += "<td>" + parseFloat(b.payout_multiplier).formatEx(8) + " x</td>";
		// bet_amount
		html += "<td class='hidden-phone'><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">";
		html += (is_win ? '+' : '-') + parseIntEx(Math.abs(b.bet_amount)/COIN) + '<small>.' + (b.bet_amount % COIN).toZeroFillIntStr(8) + "</small></span></td>";
		// profit
		html += "<td class='hidden-phone'><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">";
		html += (is_win ? '+' : '-') + parseIntEx(Math.abs(b.profit)/COIN) + '<small>.' + (b.profit % COIN * (is_win?1:-1)).toZeroFillIntStr(8) + "</small></span></td>";
		// dice_points
		html += "<td><span class=\"text-" + (is_win ? 'win' : 'lose') + "\">" + b.dice_points + "</span></td>";
		// target
		html += "<td>" +(b.is_roll_high ? '&gt;' : '&lt;');
		html +=  (b.is_roll_high ? b.dice_target_high : b.dice_target_low) + "</td>";
		html += "</tr>";
		
		// roll dice
//		for (var i = 0; i <= 10; i++) {
//			setTimeout(function() { simple_roll_dice(Math.round(randomEx()*10) + 2); }, 200);
//		}
		g_simple_dice_timer && clearInterval(g_simple_dice_timer);
		simple_roll_dice(b.dice_points);
		
		// add to table list
		$("#bet_list_simple tbody").prepend(html);
		if ($("#bet_list_simple tbody").children().length >= 200) {
			$("#bet_list_simple tbody tr:last").remove();
		}
	},
	
	/* bet_listall */
	bet_listall: function(bets) {
//		console.log(bets);
		for(var i in bets) {
			var b = bets[i];
			if (g_last_bet_id && g_last_bet_id >= parseInt(b.bet_id)) {
				continue;
			} else {
				g_last_bet_id = parseInt(b.bet_id);
			}
			
			var bet_tr_html = parser.helper_bet2html(b);
			
			// add to bet_list_all, check bets filter
			var is_add_list_all = true;
			if ((g_bet_filter.user_id  && b.user_id != g_bet_filter.user_id) ||
				((g_bet_filter.bet_min && b.bet_amount < g_bet_filter.bet_min*COIN)) ||
				((g_bet_filter.bet_max && b.bet_amount > g_bet_filter.bet_max*COIN)))
			{
				is_add_list_all = false;
			}
			if (is_add_list_all) {
				$("#bet_list_all tbody").prepend(bet_tr_html);
				if ($("#bet_list_all tbody").children().length >= 200) {
					$("#bet_list_all tbody tr:last").remove();
				}
			}
			// add to bet_list_mine
			if (g_bet_init_flag == g_bet_init_flag_arr.init_done
					&& b.user_id == g_user_id) {
				parser.helper_add_to_mine_bet(b, bet_tr_html);
				trend_draw();
			}
			
			// add to simple list
			if (g_bet_init_flag == g_bet_init_flag_arr.init_done
					&& b.user_id == g_user_id
					&& b.referer == 30000) {
				parser.helper_add_to_simple_list(b);
			}
			
		} /* for */
	}, /* /bet_listall */
	
	// helper function: add to trend data set
	helper_add_to_mine_bet: function(bet, bet_tr_html) {
		$("#bet_list_mine tbody").prepend(bet_tr_html);
		if ($("#bet_list_mine tbody").children().length >= 200) {
			$("#bet_list_mine tbody tr:last").remove();
		}
		var cur_len = g_trend_bets_data.labels.length;
		// label
		g_trend_bets_data.labels = [];
		for (var i = Math.min(cur_len + 1, 50); i >= 1; i--) {
			g_trend_bets_data.labels.push(i + '');
		}
		// data
		var is_high = parseIntEx(bet.is_roll_high) ? true : false;
		var bet_obj = {
			    win_chance: bet.chance_to_win / 1000000,
			    lucky_no:   bet.lucky_number / 10000,
			    is_high:    is_high,
			    payout:     bet.payout_multiplier,
			    bet_amount: bet.bet_amount/COIN,
			    profit:     bet.profit/COIN,
			    is_win:     parseIntEx(bet.is_win) ? true : false,
			    target:     (is_high ? '>' : '<') + (is_high ? bet.target_high : bet.target_low)/10000
		};
//		console.log(bet_obj);
		g_trend_bets_data.datasets[0].data.push(bet_obj);
		if (g_trend_bets_data.datasets[0].data.length > 50) {
			g_trend_bets_data.datasets[0].data.shift();
		}
	},
	
	/* bet_listmine */
	bet_listmine: function(bets) {
		for(var i in bets) {
			var b = bets[i];
			var bet_tr_html = parser.helper_bet2html(b);
			parser.helper_add_to_mine_bet(b, bet_tr_html);
		}
		trend_draw();
	}, /* /bet_listmine */
	
	chat_listall: function(chats) {
		var chat_list_all = $("#chat_list_all");
		for(var i in chats) {
			var b = chats[i];
			if (g_last_chat_id && g_last_chat_id >= parseInt(b.chat_id)) {
				continue;
			} else {
				g_last_chat_id = parseInt(b.chat_id);
			}
			var html = '';
			var time_diff = b.creation_time_int - g_last_show_chat_time;
			if (time_diff > 60) {
				// print time
				html += '<li class="date-holder text-center"><span class="date">';
				var t = new Date(b.creation_time_int * 1000);
				if (time_diff > 3600) {
					html += t.getFullYear() +'-' + (t.getMonth()+1).toZeroFillIntStr(2) + '-' + t.getDate().toZeroFillIntStr(2) + ' ';
				}
				html += t.getHours().toZeroFillIntStr(2) + ':' + t.getMinutes().toZeroFillIntStr(2) + ':' + t.getSeconds().toZeroFillIntStr(2);
				html += '</span></li>';
				g_last_show_chat_time = b.creation_time_int;
			}
			html += "<li class=\"";
			html += ((g_user_id == b.user_id || $.cookie('tmp_guest_id') == b.user_id) ? ' you ' : '') + "\" >";
			html += '<span class="user">';
			if (b.user_id > 100000000) {
				html += b.nickname + '(Guest)';
			} else if (b.nickname) {
				html += b.nickname + '(' + b.user_id + ')';
			} else {
				html += '(' + (b.user_id > 100000000 ? 'Guest' : b.user_id) + ')';
			}
			html += '</span>';
			var print_msg = replaceURLWithHTMLLinks(b.message);
			html += '<p>' + print_msg.replace(/<\/?script>/ig, '') + '</p>';
			html += "</li>";
			
			chat_list_all.append(html);
			if (chat_list_all.children().length >= 500) {
				chat_list_all.find('li:first-child').remove();
			}
			
			if (g_bet_init_flag_arr.chats_list == 0) {
				if ($('body').hasClass('chatting') == true) {
					g_chat_unread_count = 0;
					$(".chat-header sup").html('0').hide();
				} else {
					g_chat_unread_count++;
					$(".chat-header sup").html(g_chat_unread_count > 100 ? '100+' : g_chat_unread_count).show();
				}
			}
		} /* /for */
		chat_list_all.parent().scrollTop(chat_list_all.height());
	}, /* chat_listall */
	
}; /* /parer */


var g_msg_on_road = { count: 0, last_send_time: 0 };

function get_referer(referer) {
	var r = {'10000': 'MAN', '10001': 'AUTO', '30000': 'SIMPLE'};
	if (r[referer] != undefined) {
		return r[referer];
	}
	return 'unknown';
}

function emit_msg(path, params, method) {
	var obj = {};
	obj.path = path;
	obj.method = method || "GET";
	obj.params = params || {};
	obj.params.token = obj.params.token || g_token;
	
	// add counter
	g_msg_on_road.count += 1;
	g_msg_on_road.last_send_time = new Date().getTime();
	
	socket.emit('message', obj);
}

// show loading if still wait for message
setInterval(function() {
	var now_int = new Date().getTime();
	if (g_msg_on_road.count > 0 && now_int - g_msg_on_road.last_send_time > 5000) {
		$("#loading").fadeIn();
	} else if (g_msg_on_road.count <= 0) {
		$("#loading").hide();
	}
}, 1000);


function close_alert() {
	$("#alert_box").hide();
}


var g_show_alert_timer = null;
function show_alert(msg, leave_seconds) {
	alert_clear_timeout();
	
	var alert_box = $("#alert_box");
	alert_box.find('p').html(msg);
	alert_box.find('strong').html('Info');
	alert_box.removeClass('alert-success').removeClass('alert-error').fadeIn();
	alert_fade_out(leave_seconds);
};

function show_alert_error(msg, leave_seconds) {
	alert_clear_timeout();
	
	var alert_box = $("#alert_box");
	alert_box.find('p').html(msg);
	alert_box.find('strong').html('Error');
	alert_box.removeClass('alert-success').addClass('alert-error').fadeIn();
	alert_fade_out(leave_seconds);
};

function show_alert_success(msg, leave_seconds) {
	alert_clear_timeout();
	
	var alert_box = $("#alert_box");
	alert_box.find('p').html(msg);
	alert_box.find('strong').html('Success');
	alert_box.removeClass('alert-error').addClass('alert-success').fadeIn();
	alert_fade_out(leave_seconds);
};

function alert_fade_out(leave_seconds) {
	var sec = (leave_seconds === undefined) ? 5000 : leave_seconds;
	if (sec != 0) {
		g_show_alert_timer = setTimeout(function() { $("#alert_box").fadeOut(); }, sec);
	}
}

function alert_clear_timeout() {
	if (g_show_alert_timer) {
		clearTimeout(g_show_alert_timer);
		g_show_alert_timer = null;
	}
}


function is_user_login() {
	if (g_token) { return true; }
	return false;
}

function is_beting_page() {
	if ($("#play")[0] != undefined) {
		return true;
	}
	return false;
}


function play_music_won() {
	g_jplayer.jPlayer("setMedia", { mp3: "/audio/win.mp3"});
	g_jplayer.jPlayer("play");
}

function play_music_loss() {
	g_jplayer.jPlayer("setMedia", { mp3: "/audio/roll_dice.mp3"});
	g_jplayer.jPlayer("play");
}

/* handle message */                          
socket.on('message', function (msg) {
	// boradcast ignore counter
	if (!(msg.path == '/chat/broadcast/' || msg.path == '/bet/broadcast/' || msg.path == '/jackpot/broadcast/')) {
		g_msg_on_road.count -= 1;
	}
	
	if (msg.path == undefined || g_callback[msg.path] == undefined) {
		//console.log("msg is not available or can't find callback function");
		//console.log(msg);
		return;
	}
	if (msg.content == undefined) {
		//console.log("msg.content is null");
		return;
	}
	var content = msg.content;
	if (content.error_no == 90000) { /* can't find user by token, please relogin */
		if (window.location.pathname != '/login/') {
			window.location = '/login/';
		}
		return;
	}
	/* ingore some msg.path, let they callback function handle */
	if (!(msg.path == '/user/bindpw/'  || msg.path == '/user/bindemail/' 
		|| msg.path == '/user/bindga/' || msg.path == '/user/changepw/')) {
		if (content.error_no != 0) {
			show_alert_error(content.error_msg);
			return;
		}
		if (content.result) {
//			console.log("callback: " + msg.path);
			g_callback[msg.path](content.result);
		}
	} else {
		g_callback[msg.path](content);
	}
	
});

var g_last_bet_id   = 0;
var g_last_chat_id  = 0;
var g_is_lock_bet   = 1;  // default is lock
var g_watch_user_id = g_user_id;
var g_martingale = {
	is_running: 0, is_paused: 0,
	win_odds: 0, payout: 0, start_bet: 0, multiper: 0, max_bet: 0,
	roll_type: 1, loss_multiper: 0, win_multiper: 1,
	stop_win_profit: 0, stop_loss_profit: 0, interval_sec: 0, this_loop: {}
};

var g_bet_filter = { user_id: 0, bet_min: 0, bet_max: 0 };

var g_lucky_num = [];
while (g_lucky_num.length < 50) {
	g_lucky_num.push(50);
}

/*
 * draw 
 */
var g_plot;

/* check client seed */
var g_client_seed;
var g_bet_size_factor = 2;
var g_key_active_obj = null;

//
// 01: bets_list
// 02: chats_list
// 04: user_info
// 08: site_info
// 16: bets_listmine
//    when done, reset to zero
//
var g_bet_init_flag_arr = { 
		bets_list: 0x01, chats_list: 0x02, user_info: 0x04, site_info: 0x08,
		bets_listmine: 0x10,
		init_all: 0x1f, init_done: 0xff
};
var g_bet_init_flag = 0x00;


// check if init all works, unlock
function check_init() {
	if (g_bet_init_flag != g_bet_init_flag_arr.init_all ||
		g_bet_init_flag == g_bet_init_flag_arr.init_done) {
		return;
	}
	// init done
	$("#loading").hide();
	unlock_bet();
	g_bet_init_flag = g_bet_init_flag_arr.init_done;
}


function lock_bet() {
	$("#bet_buttons button").addClass('disabled');
	$("#mtg_btns button").addClass('disabled');
	$("#simple_btns button").addClass('disabled');
	g_is_lock_bet = 1;
}

function unlock_bet() {
	if (is_chatting()) { return; }
	$("#bet_buttons button").removeClass('disabled');
	$("#mtg_btns button").removeClass('disabled');
	$("#simple_btns button").removeClass('disabled');
	g_is_lock_bet = 0;
}

function is_bet_locking() {
	if (g_is_lock_bet || is_chatting()) {
		return true;
	}
	return false;
}

function is_chatting() {
	if ($('body').hasClass('chatting') == true) {
		return true;
	}
	return false;
}

function get_site_max_profit() {
	return parseFloat($("#site_max_bet_profit").html().replace(',', '').replace(/<[^>]*>/ig, ''));
}

function focusMoveEnd(obj, length) {
	if (obj.setSelectionRange) {
		//obj.focus();
		obj.selectionStart = obj.selectionEnd = length;
	}
	else if (obj.createTextRange) {
		var range = obj.createTextRange();
		range.collapse(true);
		//range.moveStart('character', length);
		range.moveEnd('character', length);
		range.select();
	}
}

function client_nonce(new_client_nonce) {
	var client_nonce;
	if (new_client_nonce != undefined) {
		client_nonce = new_client_nonce;
	} else {
		client_nonce = $.cookie('client_nonce') || 0;
		client_nonce++;
	}
	$.cookie('client_nonce', client_nonce, {expires: 360, path: '/'});
	$("#client_nonce").val(client_nonce);
	return client_nonce;
};

function change_client_seed(new_client_seed) {
	var client_seed = new_client_seed || util.random_str(20);
	$.cookie('client_seed', client_seed, {expires: 360, path: '/'});
	g_client_seed = client_seed;
	$("#client_seed").val(client_seed);
	client_nonce(0);  // reset client nonce to zero
}

function bet_do(is_roll_high) {
	if ($("#simpleBets").is(":visible")) {
		$("#for_myBets").click();
	}
	if (g_is_lock_bet == 1) { return; }

	// check params
	if ($('#win_odds').val() <= 0 || $('#win_odds').val() >= 980000) {
		show_alert_error("win odds is invalid");return;
		$('#win_odds').parent().addClass('error');
	}
	if ($('#bet_amount').val() < 0) {
		show_alert_error("bet amount is invalid");return;
		$('#bet_amount').parent().addClass('error');
	}
	
	lock_bet();
	
	var params = {};
	params.client_seed   = g_client_seed; 
	params.client_nonce  = client_nonce(); 
	params.chance_to_win = parseIntEx(new BigNumber($('#win_odds').val()).times(10000).toString());
	params.bet_amount    = parseIntEx(new BigNumber($('#bet_amount').val()).times(COIN).toString());
	params.is_roll_high  = is_roll_high;
	params.referer       = 10000;
	emit_msg('/bet/do/', params);
	
	if (is_roll_high) {
		$("#btn_roll_high").addClass('disabled');
	} else {
		$("#btn_roll_low").addClass('disabled');
	}
//	if (!$("#sg_bet_list_mine").is(":visible")) {
//		$("#tab_bet_list_mine").click();
//	}
};

function refresh_plot() {
//	plot.setData([
//		  			getLuckyNum(), 
//		  			{data: getLuckNumLines(1), lines: { show: true, lineWidth:1 }, points: { show: false}},
//		  			{data: getLuckNumLines(0), lines: { show: true, lineWidth:1 }, points: { show: false}}
//	]);
//	plot.draw();
};

function refresh_bet_options() {
	var win_odds = $('#win_odds').val()*1.0;
	if (win_odds > config.bet.max_win_odds) {
		win_odds = config.bet.max_win_odds;
		$('#win_odds').val(config.bet.max_win_odds);
	} else if (win_odds < config.bet.min_win_odds) {
		win_odds = config.bet.min_win_odds;
		$('#win_odds').val(config.bet.min_win_odds);
	}
	var mul         = new BigNumber(util.multiper(win_odds));
	var bet_amount  = $("#bet_amount").val()*1.0;
	var user_balance = get_balance();
	
	$('#payout').val(mul.toString());
	var bet_profit = (mul.minus(1).times(bet_amount).toString()*1.0).toFixedEx(8);
	$('#bet_profit').val(bet_profit);
	
	var roll_hi  = (100 - win_odds - 0.0001).toFixedEx(4);
	$("#roll_low").html('&lt;&nbsp;' + win_odds.toFixedEx(4));
	$("#roll_high").html('&gt;&nbsp;' + roll_hi);
	
	var site_max_profit = get_site_max_profit();
	// can't bet
	if ((bet_amount > 0 && bet_profit < 1/COIN) ||  /* profix is zero */ 
		bet_profit > site_max_profit ||         /* profit is more than site profit */
		(user_balance > 0 && user_balance < bet_amount))
	{
		lock_bet();
		
    	// show error
    	if (bet_profit > site_max_profit) {
    		show_alert_error("profit is more than site's max profit, reduce win odds OR bet amount");
    		$('#bet_profit').parent().addClass('error');
    	} else if (user_balance < bet_amount) {
    		$("#bet_amount").val(user_balance.toFixedEx(8));
    		setTimeout(refresh_bet_options, 0);
    		return;
    	} else if (bet_amount > 0 && bet_profit < 1/COIN) {
    		show_alert_error("you profit is too small, if you win your profit is still zero");
    		$('#bet_profit').parent().addClass('error');
    	}
	} else {
		/* ready for bet */
//		if (!is_bet_locking()) {
		close_alert();
		$("#manual div.error").removeClass("error");
		unlock_bet();
//		}
	}
//	refresh_plot();
	$.cookie('win_odds', win_odds.toFixedEx(4), {expires: 30, path: '/'});
	$.cookie('payout',   mul.toString(), {expires: 30, path: '/'});
	$.cookie('bet_amount', bet_amount.toFixedEx(8), {expires: 30, path: '/'});
}


function get_balance() {
	if (!$('#user_btc_amount')[0]) {
		return 0;
	}
	var balance = $('#user_btc_amount').html().replace(',', '').replace(/<[^>]*>/ig, '');
	return new BigNumber(balance).toString().toFixedEx(8) * 1.0;
}

function win_odds_min() {
	// automatically cut
	var bet_amount  = $("#bet_amount").val().toFixedEx(8);
	$('#win_odds').val(util.win_odds_min(bet_amount, get_site_max_profit()));
	refresh_bet_options();
}
function win_odds_max() {
	var win_odds_max = util.win_odds_max($("#bet_amount").val().toFixedEx(8));
	win_odds_max = new BigNumber(win_odds_max);
	$('#win_odds').val(win_odds_max.cmp(config.bet.max_win_odds) == 1 ? config.bet.max_win_odds : win_odds_max.toString().toFixedEx(4));
	refresh_bet_options();
}
function win_odds_sub() {
	var win_odds = $('#win_odds').val();
	if (win_odds > 1) {
		$('#win_odds').val((win_odds - 1.0).toFixedEx(4));
	} else {
		$('#win_odds').val(config.bet.min_win_odds);
	}
	refresh_bet_options();
}
function win_odds_add() {
	var win_odds = $('#win_odds').val()*1.0;
	if (win_odds <= 97) {
		$('#win_odds').val((1.0 + win_odds).toFixedEx(4));
	} else {
		$('#win_odds').val(config.bet.max_win_odds);
	}
	refresh_bet_options();
}


function bet_size_min() {
	var min_bet_amount = util.bet_amount_min($('#win_odds').val()*1.0);
	if (get_balance() > 0) {
		var final_bet_amount = Math.max(config.bet.min_bet_amount, min_bet_amount);
		$('#bet_amount').val(final_bet_amount.toFixedEx(8));
	} else {
		$('#bet_amount').val(0);
	}
	refresh_bet_options();
}
function bet_size_max() {
	var win_odds = $('#win_odds').val()*1.0;
	var max_bet_amount = new BigNumber(util.bet_amount_max(win_odds, get_site_max_profit()));
	$('#bet_amount').val(max_bet_amount.cmp(get_balance()) == 1 ? get_balance() : max_bet_amount.toString().toFixedEx(8));
	refresh_bet_options();
}
function bet_size_div() {
	var amount = $("#bet_amount").val() * 1.0;
	if (get_balance() == 0) {
		$("#bet_amount").val(0);
	} else if (amount >= config.bet.min_bet_amount * g_bet_size_factor) {
		$("#bet_amount").val((amount / g_bet_size_factor).toFixedEx(8));
	} else {
		$("#bet_amount").val(config.bet.min_bet_amount.toFixedEx(8));
	}
	refresh_bet_options();
}
function bet_size_mul() {
	var user_btc_amount = get_balance();
	var amount = $("#bet_amount").val() * 1.0;
	if (amount * g_bet_size_factor <= get_balance()) {
		$("#bet_amount").val((amount * g_bet_size_factor).toFixedEx(8));
	} else {
		$("#bet_amount").val(user_btc_amount.toFixedEx(8));
	}
	refresh_bet_options();
}

function bet_size_factor_up() {
	g_bet_size_factor++;
	$("#bet_size_mul").html('x' + g_bet_size_factor);
	$("#bet_size_div").html('/' + g_bet_size_factor);
}
function bet_size_factor_down() {
	if (g_bet_size_factor > 2) {
		g_bet_size_factor--;
	}
	$("#bet_size_mul").html('x' + g_bet_size_factor);
	$("#bet_size_div").html('/' + g_bet_size_factor);
}


function save_bets_filter() {
	var f_user_id = $("#filter_user_id").val();
	var f_bet_min = $("#filter_bet_min").val();
	var f_bet_max = $("#filter_bet_max").val();
	g_bet_filter.user_id = f_user_id > 0 ? f_user_id : 0;
	g_bet_filter.bet_min = f_bet_min > 0 ? f_bet_min : 0;
	g_bet_filter.bet_max = f_bet_max > 0 ? f_bet_max : 0;
	$("#btn_bets_filter").html("Saving..").attr("disabled", "disabled");
	setTimeout(function() {
		$("#btn_bets_filter").html("Save").removeAttr("disabled");
	}, 200);
}


function do_martingale() {
	if (g_martingale.is_running == 0 || g_martingale.is_paused == 1) { return; }
	
	var is_win_enough  = g_martingale.this_loop.profit >= g_martingale.stop_win_profit;
	var is_loss_enough = g_martingale.this_loop.profit <= g_martingale.stop_loss_profit;
	
	if (is_win_enough || is_loss_enough) {
		if (is_win_enough) {
			play_music_won();
			setTimeout(function() {  // use setTimeout unless the alert box will not come out
				show_alert_success("Congratulations! You won " + g_martingale.this_loop.profit.toFixedEx(8) + " BTC");
			}, 0);
		} else {
			play_music_loss();
			setTimeout(function() {  // use setTimeout unless the alert box will not come out
				show_alert("Profit reached max loss profit");
			}, 0);
			$("#mtg_cur_profit").parent().addClass('error');
		}
		mtg_stop();  // stop martingale
		return;
	}
	
	var bet_amount = g_martingale.this_loop.last_bet_amount;
	if (bet_amount == 0 ||  // first bet
		// last bet is lose and next bet will reach max bet
		g_martingale.this_loop.is_last_win ||
		bet_amount * g_martingale.loss_multiper > g_martingale.max_bet
	) {
		bet_amount = g_martingale.start_bet;
	} else {
		bet_amount *= g_martingale.loss_multiper;
	}
	
	var params = {};
	params.client_seed   = g_client_seed;
	params.client_nonce  = client_nonce();
	params.chance_to_win = parseIntEx(g_martingale.win_odds * 10000);
	params.bet_amount    = parseIntEx(bet_amount * COIN);
	params.is_roll_high  = g_martingale.roll_type;
	params.referer       = 10001;  // referer: martingale
	emit_msg('/bet/do/', params);
};

function mtg_get_options() {
	var win_odds  = $("#mtg_win_odds").val() * 1.0;
	var payout    = $("#mtg_payout").val() * 1.0;
	var start_bet = $("#mtg_start_bet").val() * 1.0;
	var loss_multiper = $("#mtg_loss_multiper").val() * 1.0;
//	var win_multiper  = $("#mtg_win_multiper").val() * 1.0;
	var max_bet   = $("#mtg_max_bet").val() * 1.0;
	var stop_win_profit  = $("#mtg_stop_win_profit").val() * 1.0;
	var stop_loss_profit = $("#mtg_stop_loss_profit").val() * 1.0;
	var interval_sec = $("#mtg_interval_sec").val() * 1.0;
	if (interval_sec <= 0) { interval_sec = 0; }
	
	// delay dust bet
	var start_bet_big = new BigNumber($("#mtg_start_bet").val());
	if (start_bet_big.times(COIN).cmp(1000) == -1) {
		interval_sec = 1;
		$("#mtg_interval_sec").val(1);
	}
	
	if (win_odds < config.bet.min_win_odds || win_odds > config.bet.max_win_odds) {
		show_alert_error("invalid win_odds");
		$("#mtg_win_odds").parent().addClass('error');
		return false;
	}
	if (payout > config.bet.max_payout || payout < config.bet.min_payout) {
		show_alert_error("invalid payout");
		$("#mtg_payout").parent().addClass('error');
		return false;
	}
	if (start_bet <= 0) {
		show_alert_error("invalid start bet");
		$("#mtg_start_bet").parent().addClass('error');
		return false;
	}
	if (max_bet <= 0) {
		show_alert_error("invalid max bet");
		$("#mtg_max_bet").parent().addClass('error');
		return false;
	}
	if (loss_multiper <= 0) {
		show_alert_error("invalid loss_multiper");
		$("#mtg_loss_multiper").parent().addClass('error');
		return false;
	}
	
	var site_max_profit = get_site_max_profit();
	if (stop_win_profit <= 0) {
		show_alert_error("invalid stop win profit");
		$("#mtg_stop_win_profit").parent().addClass('error');
		return false;
	}
	if (mtg_stop_loss_profit <= 0) {
		show_alert_error("invalid loss win profit");
		$("#mtg_stop_loss_profit").parent().addClass('error');
		return false;
	}
	if (mtg_stop_loss_profit > g_user_info.btc_amount/COIN) {
		show_alert_error("max lose profit is over than your balance");return false;
	}
	if ((payout -1) * max_bet > site_max_profit) {
		$("#mtg_max_bet").val((site_max_profit/payout).toFixedEx(8));
		show_alert("max bet profit is more than site's max profit, reduce it");
	}
	// remove all error css class
	$("#auto div.error").removeClass("error");
	
	var opt = {
			win_odds: win_odds, payout: payout, start_bet: start_bet, loss_multiper: loss_multiper,
			max_bet: max_bet, stop_win_profit: stop_win_profit, stop_loss_profit: stop_loss_profit,
			interval_sec: interval_sec
	}
	return opt;
}

function mtg_update_options() {
	var opt = mtg_get_options();
	if (!opt) { return false; }
	
	// reset martingale
	g_martingale.win_odds  = opt.win_odds;
	g_martingale.payout    = opt.payout;
	g_martingale.start_bet = opt.start_bet;
	g_martingale.loss_multiper    = opt.loss_multiper;
	g_martingale.max_bet          = opt.max_bet;
	g_martingale.stop_win_profit  = opt.stop_win_profit, 
	g_martingale.stop_loss_profit = -1 * opt.stop_loss_profit;
	g_martingale.interval_sec     = opt.interval_sec;
}

function mtg_bet(is_high) {
	if (is_bet_locking()) { return true; }
	var btn_obj = is_high ? $("#mtg_btn_roll_high") : $("#mtg_btn_roll_low"); 
	if (g_martingale.is_running == 1) {
		// stop
		mtg_stop();return;
	}

	if ($("#simpleBets").is(":visible")) {
		$("#for_myBets").click();
	}
	
	var opt = mtg_get_options();
	if (!opt) { return false; }
	
	// reset martingale
	g_martingale = {
		is_running: 1, is_paused: 0,
		win_odds: opt.win_odds, payout: opt.payout, start_bet: opt.start_bet,
		loss_multiper: opt.loss_multiper,
		max_bet: opt.max_bet, roll_type: (is_high ? 1 : 0),
		stop_win_profit: opt.stop_win_profit, stop_loss_profit: -1 * opt.stop_loss_profit,
		interval_sec: opt.interval_sec,
		this_loop: { bet_count: 0, profit: 0, last_bet_amount: 0, is_last_win: 0 },
		btn_obj: btn_obj
	};
	do_martingale();
	
	btn_obj.addClass('active');
	$("#mtg_pause").removeClass('disabled').addClass('playing');
	$("#mtg_stop").removeClass('disabled');
	return false;
};


function mtg_stop() {
	g_martingale.is_running = 0;
	g_martingale.btn_obj.html(g_martingale.roll_type ? 'Roll High' : 'Roll Low');
	$("#mtg_btns button").removeClass('active');
	$("#mtg_pause").addClass('disabled').removeClass('playing');
	$("#mtg_stop").addClass('disabled');
}

function mtg_pause() {
	g_martingale.is_paused  = 1;
	$("#mtg_pause").removeClass('playing');
}

function mtg_replay() {
	mtg_update_options()
	g_martingale.is_paused  = 0;
	$("#mtg_pause").addClass('playing');
	do_martingale();
}

$("#mtg_pause").click(function() {
	if (g_martingale.is_running == 0) { return; }
	if (g_martingale.is_paused == 1) {
		mtg_replay();
	} else {
		mtg_pause();
	}
});

$("#mtg_stop").click(function() {
	if (g_martingale.is_running == 0) { return; }
	mtg_stop();
});


function mtg_refresh_bet_options() {
	// delay dust bet
	var start_bet_big = new BigNumber($("#mtg_start_bet").val());
	if (start_bet_big.times(COIN).cmp(1000) == -1) {
		$("#auto .block-delay legend small").html('&gt;=1');
		if ($("#mtg_interval_sec").val()*1.0 < 1) {
			$("#mtg_interval_sec").val(1);
		}
	} else {
		$("#auto .block-delay legend small").html('&gt;=0');
	}
	
	var win_odds = $("#mtg_win_odds").val() * 1.0;
	if (win_odds > config.bet.max_win_odds) {
		win_odds = config.bet.max_win_odds;
		show_alert("invalid win_odds, reset to max win odds");
	} else if (win_odds < config.bet.min_win_odds) {
		win_odds = config.bet.min_win_odds;
		show_alert("invalid win_odds, reset to min win odds");
	}
	$("#mtg_win_odds").val(win_odds);
	$("#mtg_payout").val(util.multiper(win_odds));
};

function mtg_blur_common(obj, n) {
	obj.val((obj.val()*1.0).toFixedEx(n));
	mtg_refresh_bet_options();
};


// draw trend
var g_trend_option = {
  //Boolean - If we show the scale above the chart data     
  scaleOverlay : false,
  //Boolean - If we want to override with a hard coded scale
  scaleOverride : true,
  //** Required if scaleOverride is true **
  //Number - The number of steps in a hard coded scale
  scaleSteps : 5,
  //Number - The value jump in the hard coded scale
  scaleStepWidth : 20,
  //Number - The scale starting value
  scaleStartValue : null,
  //String - Colour of the scale line 
  scaleLineColor : "rgba(0,0,0,.1)",
  //Number - Pixel width of the scale line  
  scaleLineWidth : 1,
  //Boolean - Whether to show labels on the scale 
  scaleShowLabels : true,
  //Interpolated JS string - can access value
  scaleLabel : "<%=value%>",
  //String - Scale label font declaration for the scale label
  scaleFontFamily : "'Arial'",
  //Number - Scale label font size in pixels  
  scaleFontSize : 12,
  //String - Scale label font weight style  
  scaleFontStyle : "normal",
  //String - Scale label font colour  
  scaleFontColor : "#666",  
  ///Boolean - Whether grid lines are shown across the chart
  scaleShowGridLines : true,
  //String - Colour of the grid lines
  scaleGridLineColor : "rgba(0,0,0,.05)",
  //Number - Width of the grid lines
  scaleGridLineWidth : 1, 
  //Boolean - If there is a stroke on each bar  
  barShowStroke : true,
  //Number - Pixel width of the bar stroke  
  barStrokeWidth : 5,
  //Number - Spacing between each of the X value sets
  barValueSpacing : 5,
  //Number - Spacing between data sets within X values
  barDatasetSpacing : 1,
  //Boolean - Whether to animate the chart
  animation : false,
  //Number - Number of animation steps
  animationSteps : 60,
  //String - Animation easing effect
  animationEasing : "easeOutQuart",
  //Function - Fires when the animation is complete
  onAnimationComplete : null,
  
  bezierCurve : false,
  datasetStrokeWidth : 3,
  targetDOM : $("#trend_chart_dom")
};

var g_trend_bets_data = {
  labels : [],
  datasets : [
    {
      fillColor : "rgba(151,187,205,0)",
      strokeColor : "rgba(153,153,153,1)",
      pointColor : "rgba(102,102,102,1)",
      pointStrokeColor : "#fff",
      data : []
    }
  ]
};

var g_trend_draw = null;
function trend_draw() {
	if (g_trend_bets_data.labels.length <= 1) {
		$("#myTrend").hide();
		return;
	}
	if ($("#myTrend").is(":visible") == false) {
		$("#myTrend").fadeIn();
	}
	if (!g_trend_draw) {
		g_trend_draw = new Chart(document.getElementById("trend_chart").getContext("2d")).LetsdiceLine(g_trend_bets_data, g_trend_option);
	} else {
		g_trend_draw.redraw(g_trend_bets_data);
	}
}



var g_simple = {start_bet_amount: new BigNumber(0), profit: new BigNumber(0)};

function simple_take_it() {
	// reset bet amount
	$('#simple_bet_amount').val(g_simple.start_bet_amount.dividedBy(COIN).toString().toFixedEx(8));
	// clear profit
	g_simple.profit = new BigNumber(0);
	$('#simple_profit').val(g_simple.profit.toString().toFixedEx(8));
	simple_refresh_options();
	// disable button: btn_simple_take_it 
	$("#btn_simple_take_it").addClass('disabled');
}

function simple_refresh_options() {
	// check payout
	var payout     = parseIntEx(new BigNumber($('#simple_payout').val()).toString());
	if (payout <= 2) { payout = 2; }
	if (payout >= config.bet.max_payout) { payout = config.bet.max_payout; }
	$('#simple_payout').val(payout);
	
	// check bet amount
	var balance = new BigNumber(get_balance()).times(COIN);
	var bet_amount = new BigNumber($('#simple_bet_amount').val()).times(COIN);
	if (bet_amount.cmp(balance) == 1) {
		bet_amount = balance;
	}
	var site_max_profit = new BigNumber(get_site_max_profit()).times(COIN);
	if (bet_amount.cmp(site_max_profit) == 1) {
		bet_amount = site_max_profit;
		show_alert("bet amount reach site's max win amount");
	}
	if (g_simple.start_bet_amount == 0) {
		g_simple.start_bet_amount = bet_amount;  // init g_simple.start_bet_amount
	}
	$('#simple_bet_amount').val(bet_amount.dividedBy(COIN).toString().toFixedEx(8));
	
//	var profit = $('#simple_profit').val();
//	if (profit * 1.0 != 0) {
//		// 
//	}
}



var g_simple_dice_timer = null;

function simple_bet(is_roll_high) {
	if (!$("#simpleBets").is(":visible")) {
		$("#for_simpleBets").click();
	}
	
	if (g_is_lock_bet == 1) { return; }
	simple_refresh_options();
	
	lock_bet();
	
	var bet_amount = parseIntEx(new BigNumber($('#simple_bet_amount').val()).times(COIN));
	var payout     = parseIntEx(new BigNumber($('#simple_payout').val()).toString());
	var win_chance = new BigNumber(util.win_odds(payout)).times(10000).toString();
	
	g_simple_dice_timer && clearInterval(g_simple_dice_timer);
	g_simple_dice_timer = setInterval(function() { simple_roll_dice(Math.round(randomEx()*10) + 2); }, 50);
	
	var params = {};
	params.client_seed   = g_client_seed;
	params.client_nonce  = client_nonce();
	params.chance_to_win = parseIntEx(win_chance);
	params.bet_amount    = bet_amount;
	params.is_roll_high  = is_roll_high ? 1 : 0;
	params.referer       = 30000;  // 30000: simple mode
	
	emit_msg('/bet/do/', params);
	
	if (is_roll_high) {
		$("#btn_simple_high").addClass('disabled');
	} else {
		$("#btn_simple_low").addClass('disabled');
	}
	$("#btn_simple_take_it").addClass('disabled');
}


function simple_roll_dice(points) {
	var dice_1, dice_2;
	while (1) {
		dice_1 = parseIntEx(randomEx() * 10) % 6 + 1;
		dice_2 = points - dice_1;
		if (dice_1 >= 1 && dice_2 >= 1 && dice_1 <= 6 && dice_2 <= 6) {
			break;
		}
	}
	$('.dice').eq(0).find('img').attr('src',"img/dice/" + dice_1 + '.png');
	$('.dice').eq(1).find('img').attr('src',"img/dice/" + dice_2 + '.png');
}


$(document).ready(function() {
	/* check is in beting page */
	if (!is_beting_page()) { return false; }
	
	$("#loading").fadeIn();  // show loading
	lock_bet();              // lock bets
	
	/* simple */
	$('#btn_simple_high').click(function() { simple_bet(1); });
	$('#btn_simple_low').click(function() { simple_bet(0); });
	$('#btn_simple_take_it').click(function() {
		g_jplayer.jPlayer("setMedia", { mp3: "/audio/move.mp3"});
		g_jplayer.jPlayer("play");
		simple_take_it();
	});
	
	$('#simple_bet_amount').blur(function () {
		g_simple.start_bet_amount = new BigNumber($('#simple_bet_amount').val()).times(COIN);
		simple_take_it();
		simple_refresh_options();
	});
	$('#simple_payout').blur(function () {
		simple_take_it();
		simple_refresh_options();
	});
	
	/* chance to win */
	$('#win_odds').val(parseFloat($.cookie('win_odds')) > 0 ? parseFloat($.cookie('win_odds')) : 49.0100).blur(function(){
		// format then set back
    	$(this).val(($(this).val()*1.0).toFixedEx(4));
		refresh_bet_options();
	});
	$('#payout').val(parseFloat($.cookie('payout')) > 0 ? parseFloat($.cookie('payout')) : 2).blur(function() {
		var payout = ($(this).val()*1.0).toFixedEx(8);
		$(this).val(payout);
		$('#win_odds').val(util.win_odds(payout));
		refresh_bet_options();
	});
	
	/* bet amount */
	$("#bet_amount").val((Math.min($.cookie("bet_amount")*1.0, get_balance()) || 0).toFixedEx(8)).blur(function(){
		// format then set back
    	$(this).val(($(this).val()*1.0).toFixedEx(8));
    	refresh_bet_options();
    }).focus(function() {
		focusMoveEnd($(this)[0], $(this).val().length);
	});
    
    /* watch user id */
	$('#watch_user_id').val($.cookie('watch_user_id') || $.cookie('user_id')).keyup(function() {
		if ($(this).val() == '' && !$(this).is(":focus")) {
			$(this).val($.cookie('user_id'));
		}
		$.cookie('watch_user_id', $(this).val());
		g_watch_user_id = $(this).val();
		$("#radio_watch_user_mine").attr('checked', false);
    	$("#radio_watch_user_other").attr('checked', true);
	});
	$("#radio_watch_user_mine").change(function() {
		if ($(this).is(':checked')) {
			g_watch_user_id  = $.cookie('user_id');
		}
    });
	$("#radio_watch_user_other").change(function() {
		if ($(this).is(':checked')) {
			g_watch_user_id  = $("#watch_user_id").val();
		}
	});
	
	/* roll */
	$("#btn_roll_high").click(function() { bet_do(1); });
	$("#btn_roll_low").click(function() { bet_do(0); });
	
	/* win odds option */
	$("#bt_chance_min").click(win_odds_min);
	$("#bt_chance_max").click(win_odds_max);
	$("#bt_sub_one").click(win_odds_sub);
	$("#bt_add_one").click(win_odds_add);
	
	/* bet size option */
	$('#bet_size_min').click(bet_size_min);
	$('#bet_size_max').click(bet_size_max);
	$("#bet_size_mul").click(bet_size_mul);
	$("#bet_size_div").click(bet_size_div);
	
	/* bet size factor */
	$("#bet_size_factor_up").click(bet_size_factor_up);
	$("#bet_size_factor_down").click(bet_size_factor_down);
	
	/* keypress & keyup */
	$(document).keypress(function(e){
		if (is_bet_locking()) { return true; }
		if (!$("#manual").is(":visible")) {
			return true;
		}
		
		//console.log(e.which);
		if ((e.which > 57 || e.which < 48) 
				&& e.which != 46/*tab*/ && e.which != 0 && e.which != 8/*backspace*/) {
			$("#play input").blur();
		}
		switch (e.which) {
			case 97:  /* a */
				g_key_active_obj = $("#bt_add_one");
				g_key_active_obj.addClass('active').click();
				return false;
			case 102:  /* f */
				g_key_active_obj = $("#bt_chance_min");
				g_key_active_obj.addClass('active').click();
				return false;				
			case 115:  /* s */
				g_key_active_obj = $("#bt_sub_one");
				g_key_active_obj.addClass('active').click();
				return false;
			case 100:  /* d */
				g_key_active_obj = $("#bt_chance_max");
				g_key_active_obj.addClass('active').click();
				return false;
			
			case 122:  /* z */
				g_key_active_obj = $("#bet_size_mul");
				g_key_active_obj.addClass('active').click();
				return false;
			case 118:  /* v */
				g_key_active_obj = $("#bet_size_min");
				g_key_active_obj.addClass('active').click();				
				return false;
			case 120:  /* x */
				g_key_active_obj = $("#bet_size_div");
				g_key_active_obj.addClass('active').click();
				return false;
			case 99:   /* c */
				g_key_active_obj = $("#bet_size_max");
				g_key_active_obj.addClass('active').click();
				return false;
			
			case 104:  /* h */
				if (g_is_lock_bet == 1) { return false; }
				$("#btn_roll_high").click();
				return false;
			case 108:  /* l */
				if (g_is_lock_bet == 1) { return false; }
				$("#btn_roll_low").click();
				return false;
			case 112:
				change_client_seed();return false;
			default: break;
		}
	});
	
	/* keyup */
	$(document).keyup(function(e){
		// clear obj, remove class active
		if (g_key_active_obj) {
			g_key_active_obj.removeClass("active");
		}
		g_key_active_obj = null;
		return true;
	});
	
	/* bets filter */
	$("#btn_bets_filter").click(save_bets_filter);
	$("#filter_user_id").blur(save_bets_filter);
	$("#filter_bet_min").blur(save_bets_filter);
	$("#filter_bet_max").blur(save_bets_filter);
	
	/* martingale */
	$("#mtg_win_odds").blur(function() { mtg_blur_common($(this), 4); });
	$("#mtg_start_bet").blur(function() { mtg_blur_common($(this), 8); });
	$("#mtg_max_bet").blur(function() { mtg_blur_common($(this), 8); });
	$("#mtg_stop_win_profit").blur(function() { mtg_blur_common($(this), 8); });
	$("#mtg_stop_loss_profit").blur(function() { mtg_blur_common($(this), 8); });
	
	$("#mtg_payout").blur(function() {
		var payout = ($(this).val() * 1.0).toFixedEx(8);
		$(this).val(payout);
		if (payout > config.bet.max_payout) {
			$(this).val(config.bet.max_payout.toFixedEx(8));
			show_alert_error("invalid payout, reset to max payout");
		} else if (payout < config.bet.min_payout) {
			$(this).val(config.bet.min_payout.toFixedEx(8));
			show_alert_error("invalid payout, reset to min payout");
		}
		// set win_odds, than reflesh
		$("#mtg_win_odds").val(util.win_odds(payout));
		mtg_refresh_bet_options();
	});
	
	$("#mtg_btn_roll_high").click(function() { mtg_bet(1); });
	$("#mtg_btn_roll_low") .click(function() { mtg_bet(0); });
	
	refresh_bet_options();
}); /*/$(document).ready() */


/* jackpot moving */
var g_jackpot_mv_speed = 0;

$(document).ready(function(){
	/* logout */
	$("#logout").click(function() {
		// write cookie
		$.removeCookie('token',     { path: '/' });
		$.removeCookie('user_hash', { path: '/' });
		$.removeCookie('user_id',   { path: '/' });
		window.location = "/login/";
	});
	
	/* show jackpot */
	$('.static-inpot').click(function(){
        $('.inpot-popover').toggle();
	});
	
	// timezone
	$("#timezone_list a").click(function() {
		var offset = $(this).attr('title');
		$.cookie('timezone', offset, {expires: 360, path: '/'});
		$("#timezone_offset").html(offset + '<span class="caret"></span>');
		$(".timezone-menu").removeClass('open');
		location.reload();
		return false;
	});
	
	// language
	$("#locate_lang_list a").click(function() {
		$.cookie('locate_lang', $(this).attr('title'), {expires: 360, path: '/'});
		$("#locate_lang").html($(this).html() + '<span class="caret"></span>');
		$(".language-menu").removeClass('open');
		location.reload();
		return false;
	});

	/* check client seed */
	g_client_seed = $.cookie('client_seed');
	if (g_client_seed == undefined) {
	  change_client_seed();
	}
	$("#client_seed").val(g_client_seed).blur(function() {
		change_client_seed($(this).val());
	});
	/* client nonce */
	$("#client_nonce").val($.cookie('client_nonce') || 0);  // init client_nonce
	
	/*
	 * randomize
	 */
	// client seed randomize
	$("#clientSeedRandomize").click(function() {change_client_seed();});
	// server seed randomize
	$("#serverSeedRandomize").click(function() {
		// '/bet/newsrvseed/'
		$("#loading").show();
		emit_msg('/bet/newsrvseed/', {});
	});
	
	// move jackpot
	setInterval(function () {
		var inpot_title = $(".static-inpot .title");
		var middle_width = ($(".static-inpot").width() + 60)/2;
		var jackpot_amount = parseFloat($("#site_jackpot_amount span").html().replace(',', '').replace(/<[^>]*>/ig, ''));
		if (jackpot_amount < 1) { return; } 
		var now_width = parseInt(inpot_title.css('width'));
		
		if (now_width < middle_width) {
			g_jackpot_mv_speed += 0.2;
	    } else {
	    	g_jackpot_mv_speed -= 0.2;
	    }
		inpot_title.css('width', (now_width + g_jackpot_mv_speed) + 'px');
	}, 50);
	
	/**** jpalyer ****/
	g_jplayer = $("#jquery_jplayer");
	// Instance jPlayer
	g_jplayer.jPlayer({
		swfPath: "/js/jplayer",
		supplied: "mp3",
	});
	
	
	// init info
	if (is_user_login()) {
		emit_msg('/user/info/');
		setInterval(function() { emit_msg('/user/info/'); }, 1000*5);
	}
	if (is_beting_page()) {
		emit_msg('/bet/listmine/', {page_size:100});
		emit_msg('/bet/listall/', {page_size:50});
	}
	emit_msg('/site/info/');
	emit_msg('/chat/listall/', {page_size:100});
});


$(document).ready(function(){
	$('.chat-header').click(function(){
		$('body').toggleClass('chatting');
		if ($('body').hasClass('chatting') == true) {
			/* in chat */
			lock_bet();
			g_chat_unread_count = 0;
			$(".chat-header sup").html('0').hide();
			$("#input_chat").focus();
		} else {
			/* out chat */
			unlock_bet();
			refresh_bet_options();
		}
	});
	
	$('#char_form').submit(function(){
		if ($("#input_chat").val().length == 0) {
			return false;
		}
		var params = {};
		
		// for guest if need
		params.session_id  = $.cookie('PHPSESSID');
		params.guest_id    = $.cookie('tmp_guest_id');
		params.guest_name  = $.cookie('tmp_guest_name');
		params.locate_lang = $.cookie('locate_lang');
		
		params.message = $("#input_chat").val();
		emit_msg('/chat/new/', params, 'POST');
		$("#input_chat").val('').focus();
		return false;
	});
});
/*!
 * Chart.js
 * http://chartjs.org/
 *
 * Copyright 2013 Nick Downie
 * Released under the MIT license
 * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
 */

//Define the global Chart Variable as a class.
window.Chart = function(context){

	var chart = this;
	
	
	//Easing functions adapted from Robert Penner's easing equations
	//http://www.robertpenner.com/easing/
	
	var animationOptions = {
		linear : function (t){
			return t;
		},
		easeInQuad: function (t) {
			return t*t;
		},
		easeOutQuad: function (t) {
			return -1 *t*(t-2);
		},
		easeInOutQuad: function (t) {
			if ((t/=1/2) < 1) return 1/2*t*t;
			return -1/2 * ((--t)*(t-2) - 1);
		},
		easeInCubic: function (t) {
			return t*t*t;
		},
		easeOutCubic: function (t) {
			return 1*((t=t/1-1)*t*t + 1);
		},
		easeInOutCubic: function (t) {
			if ((t/=1/2) < 1) return 1/2*t*t*t;
			return 1/2*((t-=2)*t*t + 2);
		},
		easeInQuart: function (t) {
			return t*t*t*t;
		},
		easeOutQuart: function (t) {
			return -1 * ((t=t/1-1)*t*t*t - 1);
		},
		easeInOutQuart: function (t) {
			if ((t/=1/2) < 1) return 1/2*t*t*t*t;
			return -1/2 * ((t-=2)*t*t*t - 2);
		},
		easeInQuint: function (t) {
			return 1*(t/=1)*t*t*t*t;
		},
		easeOutQuint: function (t) {
			return 1*((t=t/1-1)*t*t*t*t + 1);
		},
		easeInOutQuint: function (t) {
			if ((t/=1/2) < 1) return 1/2*t*t*t*t*t;
			return 1/2*((t-=2)*t*t*t*t + 2);
		},
		easeInSine: function (t) {
			return -1 * Math.cos(t/1 * (Math.PI/2)) + 1;
		},
		easeOutSine: function (t) {
			return 1 * Math.sin(t/1 * (Math.PI/2));
		},
		easeInOutSine: function (t) {
			return -1/2 * (Math.cos(Math.PI*t/1) - 1);
		},
		easeInExpo: function (t) {
			return (t==0) ? 1 : 1 * Math.pow(2, 10 * (t/1 - 1));
		},
		easeOutExpo: function (t) {
			return (t==1) ? 1 : 1 * (-Math.pow(2, -10 * t/1) + 1);
		},
		easeInOutExpo: function (t) {
			if (t==0) return 0;
			if (t==1) return 1;
			if ((t/=1/2) < 1) return 1/2 * Math.pow(2, 10 * (t - 1));
			return 1/2 * (-Math.pow(2, -10 * --t) + 2);
			},
		easeInCirc: function (t) {
			if (t>=1) return t;
			return -1 * (Math.sqrt(1 - (t/=1)*t) - 1);
		},
		easeOutCirc: function (t) {
			return 1 * Math.sqrt(1 - (t=t/1-1)*t);
		},
		easeInOutCirc: function (t) {
			if ((t/=1/2) < 1) return -1/2 * (Math.sqrt(1 - t*t) - 1);
			return 1/2 * (Math.sqrt(1 - (t-=2)*t) + 1);
		},
		easeInElastic: function (t) {
			var s=1.70158;var p=0;var a=1;
			if (t==0) return 0;  if ((t/=1)==1) return 1;  if (!p) p=1*.3;
			if (a < Math.abs(1)) { a=1; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (1/a);
			return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p ));
		},
		easeOutElastic: function (t) {
			var s=1.70158;var p=0;var a=1;
			if (t==0) return 0;  if ((t/=1)==1) return 1;  if (!p) p=1*.3;
			if (a < Math.abs(1)) { a=1; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (1/a);
			return a*Math.pow(2,-10*t) * Math.sin( (t*1-s)*(2*Math.PI)/p ) + 1;
		},
		easeInOutElastic: function (t) {
			var s=1.70158;var p=0;var a=1;
			if (t==0) return 0;  if ((t/=1/2)==2) return 1;  if (!p) p=1*(.3*1.5);
			if (a < Math.abs(1)) { a=1; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (1/a);
			if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p ));
			return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )*.5 + 1;
		},
		easeInBack: function (t) {
			var s = 1.70158;
			return 1*(t/=1)*t*((s+1)*t - s);
		},
		easeOutBack: function (t) {
			var s = 1.70158;
			return 1*((t=t/1-1)*t*((s+1)*t + s) + 1);
		},
		easeInOutBack: function (t) {
			var s = 1.70158; 
			if ((t/=1/2) < 1) return 1/2*(t*t*(((s*=(1.525))+1)*t - s));
			return 1/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2);
		},
		easeInBounce: function (t) {
			return 1 - animationOptions.easeOutBounce (1-t);
		},
		easeOutBounce: function (t) {
			if ((t/=1) < (1/2.75)) {
				return 1*(7.5625*t*t);
			} else if (t < (2/2.75)) {
				return 1*(7.5625*(t-=(1.5/2.75))*t + .75);
			} else if (t < (2.5/2.75)) {
				return 1*(7.5625*(t-=(2.25/2.75))*t + .9375);
			} else {
				return 1*(7.5625*(t-=(2.625/2.75))*t + .984375);
			}
		},
		easeInOutBounce: function (t) {
			if (t < 1/2) return animationOptions.easeInBounce (t*2) * .5;
			return animationOptions.easeOutBounce (t*2-1) * .5 + 1*.5;
		}
	};

	//Variables global to the chart
	var width = context.canvas.width;
	var height = context.canvas.height;


	//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
	if (window.devicePixelRatio) {
		context.canvas.style.width = width + "px";
		context.canvas.style.height = height + "px";
		context.canvas.height = height * window.devicePixelRatio;
		context.canvas.width = width * window.devicePixelRatio;
		context.scale(window.devicePixelRatio, window.devicePixelRatio);
	}

	this.PolarArea = function(data,options){
	
		chart.PolarArea.defaults = {
			scaleOverlay : true,
			scaleOverride : false,
			scaleSteps : null,
			scaleStepWidth : null,
			scaleStartValue : null,
			scaleShowLine : true,
			scaleLineColor : "rgba(0,0,0,.1)",
			scaleLineWidth : 1,
			scaleShowLabels : true,
			scaleLabel : "<%=value%>",
			scaleFontFamily : "'Arial'",
			scaleFontSize : 12,
			scaleFontStyle : "normal",
			scaleFontColor : "#666",
			scaleShowLabelBackdrop : true,
			scaleBackdropColor : "rgba(255,255,255,0.75)",
			scaleBackdropPaddingY : 2,
			scaleBackdropPaddingX : 2,
			segmentShowStroke : true,
			segmentStrokeColor : "#fff",
			segmentStrokeWidth : 2,
			animation : true,
			animationSteps : 100,
			animationEasing : "easeOutBounce",
			animateRotate : true,
			animateScale : false,
			onAnimationComplete : null
		};
		
		var config = (options)? mergeChartConfig(chart.PolarArea.defaults,options) : chart.PolarArea.defaults;
		
		return new PolarArea(data,config,context);
	};

	this.Radar = function(data,options){
	
		chart.Radar.defaults = {
			scaleOverlay : false,
			scaleOverride : false,
			scaleSteps : null,
			scaleStepWidth : null,
			scaleStartValue : null,
			scaleShowLine : true,
			scaleLineColor : "rgba(0,0,0,.1)",
			scaleLineWidth : 1,
			scaleShowLabels : false,
			scaleLabel : "<%=value%>",
			scaleFontFamily : "'Arial'",
			scaleFontSize : 12,
			scaleFontStyle : "normal",
			scaleFontColor : "#666",
			scaleShowLabelBackdrop : true,
			scaleBackdropColor : "rgba(255,255,255,0.75)",
			scaleBackdropPaddingY : 2,
			scaleBackdropPaddingX : 2,
			angleShowLineOut : true,
			angleLineColor : "rgba(0,0,0,.1)",
			angleLineWidth : 1,			
			pointLabelFontFamily : "'Arial'",
			pointLabelFontStyle : "normal",
			pointLabelFontSize : 12,
			pointLabelFontColor : "#666",
			pointDot : true,
			pointDotRadius : 3,
			pointDotStrokeWidth : 1,
			datasetStroke : true,
			datasetStrokeWidth : 2,
			datasetFill : true,
			animation : true,
			animationSteps : 60,
			animationEasing : "easeOutQuart",
			onAnimationComplete : null
		};
		
		var config = (options)? mergeChartConfig(chart.Radar.defaults,options) : chart.Radar.defaults;

		return new Radar(data,config,context);
	};
	
	this.Pie = function(data,options){
		chart.Pie.defaults = {
			segmentShowStroke : true,
			segmentStrokeColor : "#fff",
			segmentStrokeWidth : 2,
			animation : true,
			animationSteps : 100,
			animationEasing : "easeOutBounce",
			animateRotate : true,
			animateScale : false,
			onAnimationComplete : null
		};		

		var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults;
		
		return new Pie(data,config,context);				
	};
	
	this.Doughnut = function(data,options){
	
		chart.Doughnut.defaults = {
			segmentShowStroke : true,
			segmentStrokeColor : "#fff",
			segmentStrokeWidth : 2,
			percentageInnerCutout : 50,
			animation : true,
			animationSteps : 100,
			animationEasing : "easeOutBounce",
			animateRotate : true,
			animateScale : false,
			onAnimationComplete : null
		};		

		var config = (options)? mergeChartConfig(chart.Doughnut.defaults,options) : chart.Doughnut.defaults;
		
		return new Doughnut(data,config,context);			
		
	};

	this.Line = function(data,options){
	
		chart.Line.defaults = {
			scaleOverlay : false,
			scaleOverride : false,
			scaleSteps : null,
			scaleStepWidth : null,
			scaleStartValue : null,
			scaleLineColor : "rgba(0,0,0,.1)",
			scaleLineWidth : 1,
			scaleShowLabels : true,
			scaleLabel : "<%=value%>",
			scaleFontFamily : "'Arial'",
			scaleFontSize : 12,
			scaleFontStyle : "normal",
			scaleFontColor : "#666",
			scaleShowGridLines : true,
			scaleGridLineColor : "rgba(0,0,0,.05)",
			scaleGridLineWidth : 1,
			bezierCurve : true,
			pointDot : true,
			pointDotRadius : 4,
			pointDotStrokeWidth : 2,
			datasetStroke : true,
			datasetStrokeWidth : 2,
			datasetFill : true,
			animation : true,
			animationSteps : 60,
			animationEasing : "easeOutQuart",
			onAnimationComplete : null
		};		
		var config = (options) ? mergeChartConfig(chart.Line.defaults,options) : chart.Line.defaults;
		
		return new Line(data,config,context);
	}
	
	this.LetsdiceLine = function(data,options){
	
		chart.LetsdiceLine.defaults = {
			scaleOverlay : false,
			scaleOverride : false,
			scaleSteps : null,
			scaleStepWidth : null,
			scaleStartValue : null,
			scaleLineColor : "rgba(0,0,0,.1)",
			scaleLineWidth : 1,
			scaleShowLabels : true,
			scaleLabel : "<%=value%>",
			scaleFontFamily : "'Arial'",
			scaleFontSize : 12,
			scaleFontStyle : "normal",
			scaleFontColor : "#666",
			scaleShowGridLines : true,
			scaleGridLineColor : "rgba(0,0,0,.05)",
			scaleGridLineWidth : 1,
			bezierCurve : true,
			pointDot : true,
			pointDotRadius : 4,
			pointDotStrokeWidth : 2,
			datasetStroke : true,
			datasetStrokeWidth : 2,
			datasetFill : true,
			animation : true,
			animationSteps : 60,
			animationEasing : "easeOutQuart",
			onAnimationComplete : null
		};		
		var config = (options) ? mergeChartConfig(chart.LetsdiceLine.defaults,options) : chart.LetsdiceLine.defaults;
		
		return new LetsdiceLine(data,config,context);
	}
	

	this.Bar = function(data,options){
		chart.Bar.defaults = {
			scaleOverlay : false,
			scaleOverride : false,
			scaleSteps : null,
			scaleStepWidth : null,
			scaleStartValue : null,
			scaleLineColor : "rgba(0,0,0,.1)",
			scaleLineWidth : 1,
			scaleShowLabels : true,
			scaleLabel : "<%=value%>",
			scaleFontFamily : "'Arial'",
			scaleFontSize : 12,
			scaleFontStyle : "normal",
			scaleFontColor : "#666",
			scaleShowGridLines : true,
			scaleGridLineColor : "rgba(0,0,0,.05)",
			scaleGridLineWidth : 1,
			barShowStroke : true,
			barStrokeWidth : 2,
			barValueSpacing : 5,
			barDatasetSpacing : 1,
			animation : true,
			animationSteps : 60,
			animationEasing : "easeOutQuart",
			onAnimationComplete : null
		};		
		var config = (options) ? mergeChartConfig(chart.Bar.defaults,options) : chart.Bar.defaults;
		
		return new Bar(data,config,context);		
	}
	
	var clear = function(c){
		c.clearRect(0, 0, width, height);
	};

	var PolarArea = function(data,config,ctx){
		var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString;		
		
		
		calculateDrawingSizes();
		
		valueBounds = getValueBounds();

		labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null;

		//Check and set the scale
		if (!config.scaleOverride){
			
			calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
		}
		else {
			calculatedScale = {
				steps : config.scaleSteps,
				stepValue : config.scaleStepWidth,
				graphMin : config.scaleStartValue,
				labels : []
			}
			populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
		}
		
		scaleHop = maxSize/(calculatedScale.steps);

		//Wrap in an animation loop wrapper
		animationLoop(config,drawScale,drawAllSegments,ctx);

		function calculateDrawingSizes(){
			maxSize = (Min([width,height])/2);
			//Remove whatever is larger - the font size or line width.
			
			maxSize -= Max([config.scaleFontSize*0.5,config.scaleLineWidth*0.5]);
			
			labelHeight = config.scaleFontSize*2;
			//If we're drawing the backdrop - add the Y padding to the label height and remove from drawing region.
			if (config.scaleShowLabelBackdrop){
				labelHeight += (2 * config.scaleBackdropPaddingY);
				maxSize -= config.scaleBackdropPaddingY*1.5;
			}
			
			scaleHeight = maxSize;
			//If the label height is less than 5, set it to 5 so we don't have lines on top of each other.
			labelHeight = Default(labelHeight,5);
		}
		function drawScale(){
			for (var i=0; i<calculatedScale.steps; i++){
				//If the line object is there
				if (config.scaleShowLine){
					ctx.beginPath();
					ctx.arc(width/2, height/2, scaleHop * (i + 1), 0, (Math.PI * 2), true);
					ctx.strokeStyle = config.scaleLineColor;
					ctx.lineWidth = config.scaleLineWidth;
					ctx.stroke();
				}

				if (config.scaleShowLabels){
					ctx.textAlign = "center";
					ctx.font = config.scaleFontStyle + " " + config.scaleFontSize + "px " + config.scaleFontFamily;
 					var label =  calculatedScale.labels[i];
					//If the backdrop object is within the font object
					if (config.scaleShowLabelBackdrop){
						var textWidth = ctx.measureText(label).width;
						ctx.fillStyle = config.scaleBackdropColor;
						ctx.beginPath();
						ctx.rect(
							Math.round(width/2 - textWidth/2 - config.scaleBackdropPaddingX),     //X
							Math.round(height/2 - (scaleHop * (i + 1)) - config.scaleFontSize*0.5 - config.scaleBackdropPaddingY),//Y
							Math.round(textWidth + (config.scaleBackdropPaddingX*2)), //Width
							Math.round(config.scaleFontSize + (config.scaleBackdropPaddingY*2)) //Height
						);
						ctx.fill();
					}
					ctx.textBaseline = "middle";
					ctx.fillStyle = config.scaleFontColor;
					ctx.fillText(label,width/2,height/2 - (scaleHop * (i + 1)));
				}
			}
		}
		function drawAllSegments(animationDecimal){
			var startAngle = -Math.PI/2,
			angleStep = (Math.PI*2)/data.length,
			scaleAnimation = 1,
			rotateAnimation = 1;
			if (config.animation) {
				if (config.animateScale) {
					scaleAnimation = animationDecimal;
				}
				if (config.animateRotate){
					rotateAnimation = animationDecimal;
				}
			}

			for (var i=0; i<data.length; i++){

				ctx.beginPath();
				ctx.arc(width/2,height/2,scaleAnimation * calculateOffset(data[i].value,calculatedScale,scaleHop),startAngle, startAngle + rotateAnimation*angleStep, false);
				ctx.lineTo(width/2,height/2);
				ctx.closePath();
				ctx.fillStyle = data[i].color;
				ctx.fill();

				if(config.segmentShowStroke){
					ctx.strokeStyle = config.segmentStrokeColor;
					ctx.lineWidth = config.segmentStrokeWidth;
					ctx.stroke();
				}
				startAngle += rotateAnimation*angleStep;
			}
		}
		function getValueBounds() {
			var upperValue = Number.MIN_VALUE;
			var lowerValue = Number.MAX_VALUE;
			for (var i=0; i<data.length; i++){
				if (data[i].value > upperValue) {upperValue = data[i].value;}
				if (data[i].value < lowerValue) {lowerValue = data[i].value;}
			};

			var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66)));
			var minSteps = Math.floor((scaleHeight / labelHeight*0.5));
			
			return {
				maxValue : upperValue,
				minValue : lowerValue,
				maxSteps : maxSteps,
				minSteps : minSteps
			};
			

		}
	}

	var Radar = function (data,config,ctx) {
		var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString;	
			
		//If no labels are defined set to an empty array, so referencing length for looping doesn't blow up.
		if (!data.labels) data.labels = [];
		
		calculateDrawingSizes();

		var valueBounds = getValueBounds();

		labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null;

		//Check and set the scale
		if (!config.scaleOverride){
			
			calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
		}
		else {
			calculatedScale = {
				steps : config.scaleSteps,
				stepValue : config.scaleStepWidth,
				graphMin : config.scaleStartValue,
				labels : []
			}
			populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
		}
		
		scaleHop = maxSize/(calculatedScale.steps);
		
		animationLoop(config,drawScale,drawAllDataPoints,ctx);
		
		//Radar specific functions.
		function drawAllDataPoints(animationDecimal){
			var rotationDegree = (2*Math.PI)/data.datasets[0].data.length;

			ctx.save();
			//translate to the centre of the canvas.
			ctx.translate(width/2,height/2);
			
			//We accept multiple data sets for radar charts, so show loop through each set
			for (var i=0; i<data.datasets.length; i++){
				ctx.beginPath();

				ctx.moveTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop)));
				for (var j=1; j<data.datasets[i].data.length; j++){
					ctx.rotate(rotationDegree);	
					ctx.lineTo(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)));
			
				}
				ctx.closePath();
				
				
				ctx.fillStyle = data.datasets[i].fillColor;
				ctx.strokeStyle = data.datasets[i].strokeColor;
				ctx.lineWidth = config.datasetStrokeWidth;
				ctx.fill();
				ctx.stroke();
				
								
				if (config.pointDot){
					ctx.fillStyle = data.datasets[i].pointColor;
					ctx.strokeStyle = data.datasets[i].pointStrokeColor;
					ctx.lineWidth = config.pointDotStrokeWidth;
					for (var k=0; k<data.datasets[i].data.length; k++){
						ctx.rotate(rotationDegree);
						ctx.beginPath();
						ctx.arc(0,animationDecimal*(-1*calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,2*Math.PI,false);
						ctx.fill();
						ctx.stroke();
					}					
					
				}
				ctx.rotate(rotationDegree);
				
			}
			ctx.restore();
			
			
		}
		function drawScale(){
			var rotationDegree = (2*Math.PI)/data.datasets[0].data.length;
			ctx.save();
		    ctx.translate(width / 2, height / 2);	
			
			if (config.angleShowLineOut){
				ctx.strokeStyle = config.angleLineColor;		    	    
				ctx.lineWidth = config.angleLineWidth;
				for (var h=0; h<data.datasets[0].data.length; h++){
					
				    ctx.rotate(rotationDegree);
					ctx.beginPath();
					ctx.moveTo(0,0);
					ctx.lineTo(0,-maxSize);
					ctx.stroke();
				}
			}

			for (var i=0; i<calculatedScale.steps; i++){
				ctx.beginPath();
				
				if(config.scaleShowLine){
					ctx.strokeStyle = config.scaleLineColor;
					ctx.lineWidth = config.scaleLineWidth;
					ctx.moveTo(0,-scaleHop * (i+1));					
					for (var j=0; j<data.datasets[0].data.length; j++){
					    ctx.rotate(rotationDegree);
						ctx.lineTo(0,-scaleHop * (i+1));
					}
					ctx.closePath();
					ctx.stroke();			
							
				}
				
				if (config.scaleShowLabels){				
					ctx.textAlign = 'center';
					ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; 
					ctx.textBaseline = "middle";
					
					if (config.scaleShowLabelBackdrop){
						var textWidth = ctx.measureText(calculatedScale.labels[i]).width;
						ctx.fillStyle = config.scaleBackdropColor;
						ctx.beginPath();
						ctx.rect(
							Math.round(- textWidth/2 - config.scaleBackdropPaddingX),     //X
							Math.round((-scaleHop * (i + 1)) - config.scaleFontSize*0.5 - config.scaleBackdropPaddingY),//Y
							Math.round(textWidth + (config.scaleBackdropPaddingX*2)), //Width
							Math.round(config.scaleFontSize + (config.scaleBackdropPaddingY*2)) //Height
						);
						ctx.fill();
					}						
					ctx.fillStyle = config.scaleFontColor;
					ctx.fillText(calculatedScale.labels[i],0,-scaleHop*(i+1));
				}

			}
			for (var k=0; k<data.labels.length; k++){				
			ctx.font = config.pointLabelFontStyle + " " + config.pointLabelFontSize+"px " + config.pointLabelFontFamily;
			ctx.fillStyle = config.pointLabelFontColor;
				var opposite = Math.sin(rotationDegree*k) * (maxSize + config.pointLabelFontSize);
				var adjacent = Math.cos(rotationDegree*k) * (maxSize + config.pointLabelFontSize);
				
				if(rotationDegree*k == Math.PI || rotationDegree*k == 0){
					ctx.textAlign = "center";
				}
				else if(rotationDegree*k > Math.PI){
					ctx.textAlign = "right";
				}
				else{
					ctx.textAlign = "left";
				}
				
				ctx.textBaseline = "middle";
				
				ctx.fillText(data.labels[k],opposite,-adjacent);
				
			}
			ctx.restore();
		};
		function calculateDrawingSizes(){
			maxSize = (Min([width,height])/2);

			labelHeight = config.scaleFontSize*2;
			
			var labelLength = 0;
			for (var i=0; i<data.labels.length; i++){
				ctx.font = config.pointLabelFontStyle + " " + config.pointLabelFontSize+"px " + config.pointLabelFontFamily;
				var textMeasurement = ctx.measureText(data.labels[i]).width;
				if(textMeasurement>labelLength) labelLength = textMeasurement;
			}
			
			//Figure out whats the largest - the height of the text or the width of what's there, and minus it from the maximum usable size.
			maxSize -= Max([labelLength,((config.pointLabelFontSize/2)*1.5)]);				
			
			maxSize -= config.pointLabelFontSize;
			maxSize = CapValue(maxSize, null, 0);
			scaleHeight = maxSize;
			//If the label height is less than 5, set it to 5 so we don't have lines on top of each other.
			labelHeight = Default(labelHeight,5);
		};
		function getValueBounds() {
			var upperValue = Number.MIN_VALUE;
			var lowerValue = Number.MAX_VALUE;
			
			for (var i=0; i<data.datasets.length; i++){
				for (var j=0; j<data.datasets[i].data.length; j++){
					if (data.datasets[i].data[j] > upperValue){upperValue = data.datasets[i].data[j]}
					if (data.datasets[i].data[j] < lowerValue){lowerValue = data.datasets[i].data[j]}
				}
			}

			var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66)));
			var minSteps = Math.floor((scaleHeight / labelHeight*0.5));
			
			return {
				maxValue : upperValue,
				minValue : lowerValue,
				maxSteps : maxSteps,
				minSteps : minSteps
			};
			

		}
	}

	var Pie = function(data,config,ctx){
		var segmentTotal = 0;
		
		//In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge.
		var pieRadius = Min([height/2,width/2]) - 5;
		
		for (var i=0; i<data.length; i++){
			segmentTotal += data[i].value;
		}
		
		
		animationLoop(config,null,drawPieSegments,ctx);
				
		function drawPieSegments (animationDecimal){
			var cumulativeAngle = -Math.PI/2,
			scaleAnimation = 1,
			rotateAnimation = 1;
			if (config.animation) {
				if (config.animateScale) {
					scaleAnimation = animationDecimal;
				}
				if (config.animateRotate){
					rotateAnimation = animationDecimal;
				}
			}
			for (var i=0; i<data.length; i++){
				var segmentAngle = rotateAnimation * ((data[i].value/segmentTotal) * (Math.PI*2));
				ctx.beginPath();
				ctx.arc(width/2,height/2,scaleAnimation * pieRadius,cumulativeAngle,cumulativeAngle + segmentAngle);
				ctx.lineTo(width/2,height/2);
				ctx.closePath();
				ctx.fillStyle = data[i].color;
				ctx.fill();
				
				if(config.segmentShowStroke){
					ctx.lineWidth = config.segmentStrokeWidth;
					ctx.strokeStyle = config.segmentStrokeColor;
					ctx.stroke();
				}
				cumulativeAngle += segmentAngle;
			}			
		}		
	}

	var Doughnut = function(data,config,ctx){
		var segmentTotal = 0;
		
		//In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge.
		var doughnutRadius = Min([height/2,width/2]) - 5;
		
		var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100);
		
		for (var i=0; i<data.length; i++){
			segmentTotal += data[i].value;
		}
		
		
		animationLoop(config,null,drawPieSegments,ctx);
		
		
		function drawPieSegments (animationDecimal){
			var cumulativeAngle = -Math.PI/2,
			scaleAnimation = 1,
			rotateAnimation = 1;
			if (config.animation) {
				if (config.animateScale) {
					scaleAnimation = animationDecimal;
				}
				if (config.animateRotate){
					rotateAnimation = animationDecimal;
				}
			}
			for (var i=0; i<data.length; i++){
				var segmentAngle = rotateAnimation * ((data[i].value/segmentTotal) * (Math.PI*2));
				ctx.beginPath();
				ctx.arc(width/2,height/2,scaleAnimation * doughnutRadius,cumulativeAngle,cumulativeAngle + segmentAngle,false);
				ctx.arc(width/2,height/2,scaleAnimation * cutoutRadius,cumulativeAngle + segmentAngle,cumulativeAngle,true);
				ctx.closePath();
				ctx.fillStyle = data[i].color;
				ctx.fill();
				
				if(config.segmentShowStroke){
					ctx.lineWidth = config.segmentStrokeWidth;
					ctx.strokeStyle = config.segmentStrokeColor;
					ctx.stroke();
				}
				cumulativeAngle += segmentAngle;
			}			
		}			
		
		
		
	}

	var Line = function(data,config,ctx){
		var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY, rotateLabels = 0;
			
		calculateDrawingSizes();
		
		valueBounds = getValueBounds();
		//Check and set the scale
		labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : "";
		if (!config.scaleOverride){
			
			calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
		}
		else {
			calculatedScale = {
				steps : config.scaleSteps,
				stepValue : config.scaleStepWidth,
				graphMin : config.scaleStartValue,
				labels : []
			}
			populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
		}
		
		scaleHop = Math.floor(scaleHeight/calculatedScale.steps);
		calculateXAxisSize();
		animationLoop(config,drawScale,drawLines,ctx);		
		
		function drawLines(animPc){
			for (var i=0; i<data.datasets.length; i++){
				ctx.strokeStyle = data.datasets[i].strokeColor;
				ctx.lineWidth = config.datasetStrokeWidth;
				ctx.beginPath();
				ctx.moveTo(yAxisPosX, xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[0],calculatedScale,scaleHop)))

				for (var j=1; j<data.datasets[i].data.length; j++){
					if (config.bezierCurve){
						ctx.bezierCurveTo(xPos(j-0.5),yPos(i,j-1),xPos(j-0.5),yPos(i,j),xPos(j),yPos(i,j));
					}
					else{
						ctx.lineTo(xPos(j),yPos(i,j));
					}
				}
				ctx.stroke();
				if (config.datasetFill){
					ctx.lineTo(yAxisPosX + (valueHop*(data.datasets[i].data.length-1)),xAxisPosY);
					ctx.lineTo(yAxisPosX,xAxisPosY);
					ctx.closePath();
					ctx.fillStyle = data.datasets[i].fillColor;
					ctx.fill();
				}
				else{
					ctx.closePath();
				}
				if(config.pointDot){
					ctx.fillStyle = data.datasets[i].pointColor;
					ctx.strokeStyle = data.datasets[i].pointStrokeColor;
					ctx.lineWidth = config.pointDotStrokeWidth;
					for (var k=0; k<data.datasets[i].data.length; k++){
						ctx.beginPath();
						ctx.arc(yAxisPosX + (valueHop *k),xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[k],calculatedScale,scaleHop)),config.pointDotRadius,0,Math.PI*2,true);
						ctx.fill();
						ctx.stroke();
					}
				}
			}
			
			function yPos(dataSet,iteration){
				return xAxisPosY - animPc*(calculateOffset(data.datasets[dataSet].data[iteration],calculatedScale,scaleHop));			
			}
			function xPos(iteration){
				return yAxisPosX + (valueHop * iteration);
			}
		}
		function drawScale(){
			//X axis line
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(width-widestXLabel/2+5,xAxisPosY);
			ctx.lineTo(width-(widestXLabel/2)-xAxisLength-5,xAxisPosY);
			ctx.stroke();
			
			
			if (rotateLabels > 0){
				ctx.save();
				ctx.textAlign = "right";
			}
			else{
				ctx.textAlign = "center";
			}
			ctx.fillStyle = config.scaleFontColor;
			for (var i=0; i<data.labels.length; i++){
				ctx.save();
				if (rotateLabels > 0){
					ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize);
					ctx.rotate(-(rotateLabels * (Math.PI/180)));
					ctx.fillText(data.labels[i], 0,0);
					ctx.restore();
				}
				
				else{
					ctx.fillText(data.labels[i], yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize+3);					
				}

				ctx.beginPath();
				ctx.moveTo(yAxisPosX + i * valueHop, xAxisPosY+3);
				
				//Check i isnt 0, so we dont go over the Y axis twice.
				if(config.scaleShowGridLines && i>0){
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;					
					ctx.lineTo(yAxisPosX + i * valueHop, 5);
				}
				else{
					ctx.lineTo(yAxisPosX + i * valueHop, xAxisPosY+3);				
				}
				ctx.stroke();
			}
			
			//Y axis
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(yAxisPosX,xAxisPosY+5);
			ctx.lineTo(yAxisPosX,5);
			ctx.stroke();
			
			ctx.textAlign = "right";
			ctx.textBaseline = "middle";
			for (var j=0; j<calculatedScale.steps; j++){
				ctx.beginPath();
				ctx.moveTo(yAxisPosX-3,xAxisPosY - ((j+1) * scaleHop));
				if (config.scaleShowGridLines){
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;
					ctx.lineTo(yAxisPosX + xAxisLength + 5,xAxisPosY - ((j+1) * scaleHop));					
				}
				else{
					ctx.lineTo(yAxisPosX-0.5,xAxisPosY - ((j+1) * scaleHop));
				}
				
				ctx.stroke();
				
				if (config.scaleShowLabels){
					ctx.fillText(calculatedScale.labels[j],yAxisPosX-8,xAxisPosY - ((j+1) * scaleHop));
				}
			}
			
			
		}
		function calculateXAxisSize(){
			var longestText = 1;
			//if we are showing the labels
			if (config.scaleShowLabels){
				ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
				for (var i=0; i<calculatedScale.labels.length; i++){
					var measuredText = ctx.measureText(calculatedScale.labels[i]).width;
					longestText = (measuredText > longestText)? measuredText : longestText;
				}
				//Add a little extra padding from the y axis
				longestText +=10;
			}
			xAxisLength = width - longestText - widestXLabel;
			valueHop = Math.floor(xAxisLength/(data.labels.length-1));	
				
			yAxisPosX = width-widestXLabel/2-xAxisLength;
			xAxisPosY = scaleHeight + config.scaleFontSize/2;				
		}		
		function calculateDrawingSizes(){
			maxSize = height;

			//Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees.
			ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
			widestXLabel = 1;
			for (var i=0; i<data.labels.length; i++){
				var textLength = ctx.measureText(data.labels[i]).width;
				//If the text length is longer - make that equal to longest text!
				widestXLabel = (textLength > widestXLabel)? textLength : widestXLabel;
			}
			if (width/data.labels.length < widestXLabel){
				rotateLabels = 45;
				if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){
					rotateLabels = 90;
					maxSize -= widestXLabel; 
				}
				else{
					maxSize -= Math.sin(rotateLabels) * widestXLabel;
				}
			}
			else{
				maxSize -= config.scaleFontSize;
			}
			
			//Add a little padding between the x line and the text
			maxSize -= 5;
			
			
			labelHeight = config.scaleFontSize;
			
			maxSize -= labelHeight;
			//Set 5 pixels greater than the font size to allow for a little padding from the X axis.
			
			scaleHeight = maxSize;
			
			//Then get the area above we can safely draw on.
			
		}		
		function getValueBounds() {
			var upperValue = Number.MIN_VALUE;
			var lowerValue = Number.MAX_VALUE;
			for (var i=0; i<data.datasets.length; i++){
				for (var j=0; j<data.datasets[i].data.length; j++){
					if ( data.datasets[i].data[j] > upperValue) { upperValue = data.datasets[i].data[j] };
					if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] };
				}
			};
	
			var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66)));
			var minSteps = Math.floor((scaleHeight / labelHeight*0.5));
			
			return {
				maxValue : upperValue,
				minValue : lowerValue,
				maxSteps : maxSteps,
				minSteps : minSteps
			};
			
	
		}

		
	} /*line*/
	
  /* LetsdiceLine */
	var LetsdiceLine = function(data,config,ctx){
		var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY, rotateLabels = 0;
		/*	
		calculateDrawingSizes();
		
		valueBounds = getValueBounds();
		//Check and set the scale
		labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : "";
		if (!config.scaleOverride){
			
			calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
		}
		else {
			calculatedScale = {
				steps : config.scaleSteps,
				stepValue : config.scaleStepWidth,
				graphMin : config.scaleStartValue,
				labels : []
			}
			populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
		}
		
		scaleHop = scaleHeight/calculatedScale.steps;
		calculateXAxisSize();
		animationLoop(config,drawScale,drawLines,ctx);*/		
		
		this.redraw=function redraw(data){
			calculateDrawingSizes();
			valueBounds = getValueBounds();
			//Check and set the scale
			labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : "";
			if (!config.scaleOverride){
				
				calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
			}
			else {
				calculatedScale = {
					steps : config.scaleSteps,
					stepValue : config.scaleStepWidth,
					graphMin : config.scaleStartValue,
					labels : []
				}
				populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
			}
			
			scaleHop = scaleHeight/calculatedScale.steps;
			calculateXAxisSize();
			clear();
			animationLoop(config,drawScale,drawLines,ctx);
			config.targetDOM.show();
			return true;
		}

		this.redraw(data);
		function clear(){

			config.targetDOM.hide();
			config.targetDOM.html('');

			ctx.save();
			ctx.setTransform(1, 0, 0, 1, 0, 0);
			// Will always clear the right space
			ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
			ctx.canvas.width = ctx.canvas.width;
			ctx.restore();
			//ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

		}

		function drawDom(){

		}

		function drawLines(animPc){

			for (var i=0; i<data.datasets.length; i++){

				var max_profit = Math.abs(data.datasets[i].data[0].profit);
				var min_profit = Math.abs(data.datasets[i].data[0].profit);
				for(var j=1;j<data.datasets[i].data.length;j++){
					if (Math.abs(data.datasets[i].data[j].profit) > max_profit){
						max_profit = Math.abs(data.datasets[i].data[j].profit);
					}
					if (Math.abs(data.datasets[i].data[j].profit) < min_profit){
						min_profit = Math.abs(data.datasets[i].data[j].profit);
					}
				}
				min_profit += 0.00000001;
				max_profit += 0.00000001;

				//draw rect
				//ctx.strokeStyle = "rgba(1,1,1,1)";
				ctx.fillStyle = "rgba(247,247,247,1)";
				ctx.lineWidth = 1;
				if(data.datasets[i].data[0].is_high){
					ctx.fillRect(xPos(0),xAxisPosY-scaleHeight,xWidth(0)/2.0,data.datasets[i].data[0].win_chance*scaleHeight);
				}else{
					ctx.fillRect(xPos(0), xAxisPosY-data.datasets[i].data[0].win_chance*scaleHeight,xWidth(0)/2.0,data.datasets[i].data[0].win_chance*scaleHeight);
				}

				for (var k=1; k<data.datasets[i].data.length; k++){
					ctx.beginPath();
					if(data.datasets[i].data[k].is_high){
						ctx.fillRect(xPos(k-0.5),xAxisPosY-scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
					}else{
						ctx.fillRect(xPos(k-0.5), xAxisPosY-data.datasets[i].data[k].win_chance*scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
					}
					ctx.fill();
					ctx.stroke();
				}


				//draw rect green line
				ctx.strokeStyle = "rgba(71,153,31,1)";
				ctx.lineWidth = 0.5;
				k = 0;
				ctx.beginPath();
				if(data.datasets[i].data[k].is_high){
					ctx.moveTo(xPos(k),data.datasets[i].data[k].win_chance*scaleHeight+xAxisPosY-scaleHeight);
					ctx.lineTo(xPos(k+0.5),data.datasets[i].data[k].win_chance*scaleHeight+xAxisPosY-scaleHeight);				
				}else{
					ctx.moveTo(xPos(k),xAxisPosY-data.datasets[i].data[k].win_chance*scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
					ctx.lineTo(xPos(k+0.5),xAxisPosY-data.datasets[i].data[k].win_chance*scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
				}
				ctx.stroke();

				for (var k=1; k<data.datasets[i].data.length; k++){
					ctx.beginPath();
					if(data.datasets[i].data[k].is_high){
						ctx.moveTo(xPos(k-0.5),data.datasets[i].data[k].win_chance*scaleHeight+xAxisPosY-scaleHeight);
						ctx.lineTo(xPos(k+0.5),data.datasets[i].data[k].win_chance*scaleHeight+xAxisPosY-scaleHeight);				
					}else{
						ctx.moveTo(xPos(k-0.5),xAxisPosY-data.datasets[i].data[k].win_chance*scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
						ctx.lineTo(xPos(k+0.5),xAxisPosY-data.datasets[i].data[k].win_chance*scaleHeight,xWidth(k),data.datasets[i].data[k].win_chance*scaleHeight);
					}
					ctx.stroke();
				}

			  //draw line
				ctx.strokeStyle = data.datasets[i].strokeColor;
				ctx.lineWidth = config.datasetStrokeWidth;
				ctx.beginPath();
				ctx.moveTo(yAxisPosX, xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[0].lucky_no,calculatedScale,scaleHop)))


				for (var j=1; j<data.datasets[i].data.length; j++){
					if (config.bezierCurve){
						ctx.bezierCurveTo(xPos(j-0.5),yPos(i,j-1),xPos(j-0.5),yPos(i,j),xPos(j),yPos(i,j));
					}
					else{
						ctx.lineTo(xPos(j),yPos(i,j));
					}
				}
				ctx.stroke();
				if (config.datasetFill){
					ctx.lineTo(yAxisPosX + (valueHop*(data.datasets[i].data.length-1)),xAxisPosY);
					ctx.lineTo(yAxisPosX,xAxisPosY);
					ctx.closePath();
					ctx.fillStyle = data.datasets[i].fillColor;
					ctx.fill();
				}
				else{
					ctx.closePath();
				}

				//draw point
				if(config.pointDot){

					for (var k=0; k<data.datasets[i].data.length; k++){
						if (data.datasets[i].data[k].is_win){
							ctx.fillStyle = "rgba(71,153,31,1)";
						}else{
							ctx.fillStyle = data.datasets[i].pointColor;
						}
						ctx.strokeStyle = data.datasets[i].pointStrokeColor;
						ctx.lineWidth = config.pointDotStrokeWidth;
						ctx.beginPath();
						var r = 5;
						if (min_profit != max_profit){
							var r = 5+(Math.log(Math.abs(data.datasets[i].data[k].profit+0.00000001)/min_profit)/Math.log(max_profit/min_profit))*5;
						}
						if (isNaN(r) || r < 5){
							r = 5
						}
						ctx.arc(yAxisPosX + (valueHop *k),xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[k].lucky_no,calculatedScale,scaleHop)),r,0,Math.PI*2,true);
						ctx.fill();
						ctx.stroke();
						var label_H_or_L = 'L';
						if (data.datasets[i].data[k].is_high){
							label_H_or_L = 'H';
						}
						var color = "rgba(51,51,51,1)";
						if (data.datasets[i].data[k].is_win){
							color = "rgba(71,153,31,1)";
						}
						var temp_dom=config.targetDOM.append("<a href='#' class='invisible_pointDot' style='position:absolute;left:"+
																									(yAxisPosX + (valueHop *k)-40)+"px;top:"+
																									(xAxisPosY - animPc*(calculateOffset(data.datasets[i].data[k].lucky_no,calculatedScale,scaleHop))-40)+
																									"px;background-color:"+color+"'><span class='lable_lucky_no'>"+data.datasets[i].data[k].lucky_no+"</span>"+
																									"<span class='lable_H_or_L'>"+label_H_or_L+"</span>"+
																									"<span class='lable_target'>"+data.datasets[i].data[k].target+"</span>"+
																									"</a>");
					}
				}				
			}
			/*
			function doMouseDown(event){
				console.log(event);
			}
			ctx.addEventListener("mousedown",doMouseDown,false)/
			*/
			function yPos(dataSet,iteration){
				return xAxisPosY - animPc*(calculateOffset(data.datasets[dataSet].data[iteration].lucky_no,calculatedScale,scaleHop));			
			}
			function xPos(iteration){
				return yAxisPosX + (valueHop * iteration);
			}
			function xWidth(iteration){
				return valueHop;
			}

		}
		function drawScale(){
			//X axis line
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(width-widestXLabel/2+5,xAxisPosY);
			ctx.lineTo(width-(widestXLabel/2)-xAxisLength-5,xAxisPosY);
			ctx.stroke();
			
			
			if (rotateLabels > 0){
				ctx.save();
				ctx.textAlign = "right";
			}
			else{
				ctx.textAlign = "center";
			}
			ctx.fillStyle = config.scaleFontColor;
			for (var i=0; i<data.labels.length; i++){
				ctx.save();
				if (rotateLabels > 0){
					ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize);
					ctx.rotate(-(rotateLabels * (Math.PI/180)));
					ctx.fillText(data.labels[i], 0,0);
					ctx.restore();
				}
				
				else{
					ctx.fillText(data.labels[i], yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize+3);					
				}

				ctx.beginPath();
				ctx.moveTo(yAxisPosX + i * valueHop, xAxisPosY+3);
				
				//Check i isnt 0, so we dont go over the Y axis twice.
				if(config.scaleShowGridLines && i>0){
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;					
					ctx.lineTo(yAxisPosX + i * valueHop, 5);
				}
				else{
					ctx.lineTo(yAxisPosX + i * valueHop, xAxisPosY+3);				
				}
				ctx.stroke();
			}
			
			//Y axis
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(yAxisPosX,xAxisPosY+5);
			ctx.lineTo(yAxisPosX,5);
			ctx.stroke();
			
			ctx.textAlign = "right";
			ctx.textBaseline = "middle";
			for (var j=0; j<calculatedScale.steps; j++){
				ctx.beginPath();
				ctx.moveTo(yAxisPosX-3,xAxisPosY - ((j+1) * scaleHop));
				if (config.scaleShowGridLines){
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;
					ctx.lineTo(yAxisPosX + xAxisLength + 5,xAxisPosY - ((j+1) * scaleHop));					
				}
				else{
					ctx.lineTo(yAxisPosX-0.5,xAxisPosY - ((j+1) * scaleHop));
				}
				
				ctx.stroke();
				
				if (config.scaleShowLabels){
					ctx.fillText(calculatedScale.labels[j],yAxisPosX-8,xAxisPosY - ((j+1) * scaleHop));
				}
			}
			
			
		}
		function calculateXAxisSize(){
			var longestText = 1;
			//if we are showing the labels
			if (config.scaleShowLabels){
				ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
				for (var i=0; i<calculatedScale.labels.length; i++){
					var measuredText = ctx.measureText(calculatedScale.labels[i]).width;
					longestText = (measuredText > longestText)? measuredText : longestText;
				}
				//Add a little extra padding from the y axis
				longestText +=10;
			}
			xAxisLength = width - longestText - widestXLabel;
			valueHop = Math.floor(xAxisLength/(data.labels.length-1));	
				
			yAxisPosX = width-widestXLabel/2-xAxisLength;
			xAxisPosY = scaleHeight + config.scaleFontSize/2;				
		}		
		function calculateDrawingSizes(){
			maxSize = height;

			//Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees.
			ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
			widestXLabel = 1;
			for (var i=0; i<data.labels.length; i++){
				var textLength = ctx.measureText(data.labels[i]).width;
				//If the text length is longer - make that equal to longest text!
				widestXLabel = (textLength > widestXLabel)? textLength : widestXLabel;
			}
			if (width/data.labels.length < widestXLabel){
				rotateLabels = 45;
				if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){
					rotateLabels = 90;
					maxSize -= widestXLabel; 
				}
				else{
					maxSize -= Math.sin(rotateLabels) * widestXLabel;
				}
			}
			else{
				maxSize -= config.scaleFontSize;
			}
			
			//Add a little padding between the x line and the text
			maxSize -= 5;
			
			
			labelHeight = config.scaleFontSize;
			
			maxSize -= labelHeight;
			//Set 5 pixels greater than the font size to allow for a little padding from the X axis.
			
			scaleHeight = maxSize;
			
			//Then get the area above we can safely draw on.
			
		}		
		function getValueBounds() {
			var upperValue = Number.MIN_VALUE;
			var lowerValue = Number.MAX_VALUE;
			for (var i=0; i<data.datasets.length; i++){
				for (var j=0; j<data.datasets[i].data.length; j++){
					if ( data.datasets[i].data[j] > upperValue) { upperValue = data.datasets[i].data[j] };
					if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] };
				}
			};
	
			var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66)));
			var minSteps = Math.floor((scaleHeight / labelHeight*0.5));
			
			return {
				maxValue : upperValue,
				minValue : lowerValue,
				maxSteps : maxSteps,
				minSteps : minSteps
			};
			
	
		}
	} /*letsdiceline*/


	var Bar = function(data,config,ctx){
		var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY,barWidth, rotateLabels = 0;
			
		calculateDrawingSizes();
		
		valueBounds = getValueBounds();
		//Check and set the scale
		labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : "";
		if (!config.scaleOverride){
			
			calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString);
		}
		else {
			calculatedScale = {
				steps : config.scaleSteps,
				stepValue : config.scaleStepWidth,
				graphMin : config.scaleStartValue,
				labels : []
			}
			populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth);
		}
		
		scaleHop = Math.floor(scaleHeight/calculatedScale.steps);
		calculateXAxisSize();
		animationLoop(config,drawScale,drawBars,ctx);		
		
		function drawBars(animPc){
			ctx.lineWidth = config.barStrokeWidth;
			for (var i=0; i<data.datasets.length; i++){
					ctx.fillStyle = data.datasets[i].fillColor;
					ctx.strokeStyle = data.datasets[i].strokeColor;
				for (var j=0; j<data.datasets[i].data.length; j++){
					var barOffset = yAxisPosX + config.barValueSpacing + valueHop*j + barWidth*i + config.barDatasetSpacing*i + config.barStrokeWidth*i;
					
					ctx.beginPath();
					ctx.moveTo(barOffset, xAxisPosY);
					ctx.lineTo(barOffset, xAxisPosY - animPc*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)+(config.barStrokeWidth/2));
					ctx.lineTo(barOffset + barWidth, xAxisPosY - animPc*calculateOffset(data.datasets[i].data[j],calculatedScale,scaleHop)+(config.barStrokeWidth/2));
					ctx.lineTo(barOffset + barWidth, xAxisPosY);
					if(config.barShowStroke){
						ctx.stroke();
					}
					ctx.closePath();
					ctx.fill();
				}
			}
			
		}
		function drawScale(){
			//X axis line
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(width-widestXLabel/2+5,xAxisPosY);
			ctx.lineTo(width-(widestXLabel/2)-xAxisLength-5,xAxisPosY);
			ctx.stroke();
			
			
			if (rotateLabels > 0){
				ctx.save();
				ctx.textAlign = "right";
			}
			else{
				ctx.textAlign = "center";
			}
			ctx.fillStyle = config.scaleFontColor;
			for (var i=0; i<data.labels.length; i++){
				ctx.save();
				if (rotateLabels > 0){
					ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize);
					ctx.rotate(-(rotateLabels * (Math.PI/180)));
					ctx.fillText(data.labels[i], 0,0);
					ctx.restore();
				}
				
				else{
					ctx.fillText(data.labels[i], yAxisPosX + i*valueHop + valueHop/2,xAxisPosY + config.scaleFontSize+3);					
				}

				ctx.beginPath();
				ctx.moveTo(yAxisPosX + (i+1) * valueHop, xAxisPosY+3);
				
				//Check i isnt 0, so we dont go over the Y axis twice.
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;					
					ctx.lineTo(yAxisPosX + (i+1) * valueHop, 5);
				ctx.stroke();
			}
			
			//Y axis
			ctx.lineWidth = config.scaleLineWidth;
			ctx.strokeStyle = config.scaleLineColor;
			ctx.beginPath();
			ctx.moveTo(yAxisPosX,xAxisPosY+5);
			ctx.lineTo(yAxisPosX,5);
			ctx.stroke();
			
			ctx.textAlign = "right";
			ctx.textBaseline = "middle";
			for (var j=0; j<calculatedScale.steps; j++){
				ctx.beginPath();
				ctx.moveTo(yAxisPosX-3,xAxisPosY - ((j+1) * scaleHop));
				if (config.scaleShowGridLines){
					ctx.lineWidth = config.scaleGridLineWidth;
					ctx.strokeStyle = config.scaleGridLineColor;
					ctx.lineTo(yAxisPosX + xAxisLength + 5,xAxisPosY - ((j+1) * scaleHop));					
				}
				else{
					ctx.lineTo(yAxisPosX-0.5,xAxisPosY - ((j+1) * scaleHop));
				}
				
				ctx.stroke();
				if (config.scaleShowLabels){
					ctx.fillText(calculatedScale.labels[j],yAxisPosX-8,xAxisPosY - ((j+1) * scaleHop));
				}
			}
			
			
		}
		function calculateXAxisSize(){
			var longestText = 1;
			//if we are showing the labels
			if (config.scaleShowLabels){
				ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
				for (var i=0; i<calculatedScale.labels.length; i++){
					var measuredText = ctx.measureText(calculatedScale.labels[i]).width;
					longestText = (measuredText > longestText)? measuredText : longestText;
				}
				//Add a little extra padding from the y axis
				longestText +=10;
			}
			xAxisLength = width - longestText - widestXLabel;
			valueHop = Math.floor(xAxisLength/(data.labels.length));	
			
			barWidth = (valueHop - config.scaleGridLineWidth*2 - (config.barValueSpacing*2) - (config.barDatasetSpacing*data.datasets.length-1) - ((config.barStrokeWidth/2)*data.datasets.length-1))/data.datasets.length;
			
			yAxisPosX = width-widestXLabel/2-xAxisLength;
			xAxisPosY = scaleHeight + config.scaleFontSize/2;				
		}		
		function calculateDrawingSizes(){
			maxSize = height;

			//Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees.
			ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily;
			widestXLabel = 1;
			for (var i=0; i<data.labels.length; i++){
				var textLength = ctx.measureText(data.labels[i]).width;
				//If the text length is longer - make that equal to longest text!
				widestXLabel = (textLength > widestXLabel)? textLength : widestXLabel;
			}
			if (width/data.labels.length < widestXLabel){
				rotateLabels = 45;
				if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){
					rotateLabels = 90;
					maxSize -= widestXLabel; 
				}
				else{
					maxSize -= Math.sin(rotateLabels) * widestXLabel;
				}
			}
			else{
				maxSize -= config.scaleFontSize;
			}
			
			//Add a little padding between the x line and the text
			maxSize -= 5;
			
			
			labelHeight = config.scaleFontSize;
			
			maxSize -= labelHeight;
			//Set 5 pixels greater than the font size to allow for a little padding from the X axis.
			
			scaleHeight = maxSize;
			
			//Then get the area above we can safely draw on.
			
		}		
		function getValueBounds() {
			var upperValue = Number.MIN_VALUE;
			var lowerValue = Number.MAX_VALUE;
			for (var i=0; i<data.datasets.length; i++){
				for (var j=0; j<data.datasets[i].data.length; j++){
					if ( data.datasets[i].data[j] > upperValue) { upperValue = data.datasets[i].data[j] };
					if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] };
				}
			};
	
			var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66)));
			var minSteps = Math.floor((scaleHeight / labelHeight*0.5));
			
			return {
				maxValue : upperValue,
				minValue : lowerValue,
				maxSteps : maxSteps,
				minSteps : minSteps
			};
			
	
		}
	}
	
	function calculateOffset(val,calculatedScale,scaleHop){
		var outerValue = calculatedScale.steps * calculatedScale.stepValue;
		var adjustedValue = val - calculatedScale.graphMin;
		var scalingFactor = CapValue(adjustedValue/outerValue,1,0);
		return (scaleHop*calculatedScale.steps) * scalingFactor;
	}
	
	function animationLoop(config,drawScale,drawData,ctx){
		var animFrameAmount = (config.animation)? 1/CapValue(config.animationSteps,Number.MAX_VALUE,1) : 1,
			easingFunction = animationOptions[config.animationEasing],
			percentAnimComplete =(config.animation)? 0 : 1;
		
	
		
		if (typeof drawScale !== "function") drawScale = function(){};
		
		requestAnimFrame(animLoop);
		
		function animateFrame(){
			var easeAdjustedAnimationPercent =(config.animation)? CapValue(easingFunction(percentAnimComplete),null,0) : 1;
			clear(ctx);
			if(config.scaleOverlay){
				drawData(easeAdjustedAnimationPercent);
				drawScale();
			} else {
				drawScale();
				drawData(easeAdjustedAnimationPercent);
			}				
		}
		function animLoop(){
			//We need to check if the animation is incomplete (less than 1), or complete (1).
				percentAnimComplete += animFrameAmount;
				animateFrame();	
				//Stop the loop continuing forever
				if (percentAnimComplete <= 1){
					requestAnimFrame(animLoop);
				}
				else{
					if (typeof config.onAnimationComplete == "function") config.onAnimationComplete();
				}
			
		}		
		
	}

	//Declare global functions to be called within this namespace here.
	
	
	// shim layer with setTimeout fallback
	var requestAnimFrame = (function(){
		return window.requestAnimationFrame ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame ||
			window.oRequestAnimationFrame ||
			window.msRequestAnimationFrame ||
			function(callback) {
				window.setTimeout(callback, 1000 / 60);
			};
	})();

	function calculateScale(drawingHeight,maxSteps,minSteps,maxValue,minValue,labelTemplateString){
			var graphMin,graphMax,graphRange,stepValue,numberOfSteps,valueRange,rangeOrderOfMagnitude,decimalNum;
			
			valueRange = maxValue - minValue;
			
			rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange);

        	graphMin = Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude);
            
            graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude);
            
            graphRange = graphMax - graphMin;
            
            stepValue = Math.pow(10, rangeOrderOfMagnitude);
            
	        numberOfSteps = Math.round(graphRange / stepValue);
	        
	        //Compare number of steps to the max and min for that size graph, and add in half steps if need be.	        
	        while(numberOfSteps < minSteps || numberOfSteps > maxSteps) {
	        	if (numberOfSteps < minSteps){
			        stepValue /= 2;
			        numberOfSteps = Math.round(graphRange/stepValue);
		        }
		        else{
			        stepValue *=2;
			        numberOfSteps = Math.round(graphRange/stepValue);
		        }
	        };

	        var labels = [];
	        populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue);
		
	        return {
		        steps : numberOfSteps,
				stepValue : stepValue,
				graphMin : graphMin,
				labels : labels		        
		        
	        }
		
			function calculateOrderOfMagnitude(val){
			  return Math.floor(Math.log(val) / Math.LN10);
			}		


	}

    //Populate an array of all the labels by interpolating the string.
    function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) {
        if (labelTemplateString) {
            //Fix floating point errors by setting to fixed the on the same decimal as the stepValue.
            for (var i = 1; i < numberOfSteps + 1; i++) {
                labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))}));
            }
        }
    }
	
	//Max value from array
	function Max( array ){
		return Math.max.apply( Math, array );
	};
	//Min value from array
	function Min( array ){
		return Math.min.apply( Math, array );
	};
	//Default if undefined
	function Default(userDeclared,valueIfFalse){
		if(!userDeclared){
			return valueIfFalse;
		} else {
			return userDeclared;
		}
	};
	//Is a number function
	function isNumber(n) {
		return !isNaN(parseFloat(n)) && isFinite(n);
	}
	//Apply cap a value at a high or low number
	function CapValue(valueToCap, maxValue, minValue){
		if(isNumber(maxValue)) {
			if( valueToCap > maxValue ) {
				return maxValue;
			}
		}
		if(isNumber(minValue)){
			if ( valueToCap < minValue ){
				return minValue;
			}
		}
		return valueToCap;
	}
	function getDecimalPlaces (num){
		var numberOfDecimalPlaces;
		if (num%1!=0){
			return num.toString().split(".")[1].length
		}
		else{
			return 0;
		}
		
	} 
	
	function mergeChartConfig(defaults,userDefined){
		var returnObj = {};
	    for (var attrname in defaults) { returnObj[attrname] = defaults[attrname]; }
	    for (var attrname in userDefined) { returnObj[attrname] = userDefined[attrname]; }
	    return returnObj;
	}
	
	//Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
	  var cache = {};
	 
	  function tmpl(str, data){
	    // Figure out if we're getting a template, or if we need to
	    // load the template - and be sure to cache the result.
	    var fn = !/\W/.test(str) ?
	      cache[str] = cache[str] ||
	        tmpl(document.getElementById(str).innerHTML) :
	     
	      // Generate a reusable function that will serve as a template
	      // generator (and which will be cached).
	      new Function("obj",
	        "var p=[],print=function(){p.push.apply(p,arguments);};" +
	       
	        // Introduce the data as local variables using with(){}
	        "with(obj){p.push('" +
	       
	        // Convert the template into pure JavaScript
	        str
	          .replace(/[\r\t\n]/g, " ")
	          .split("<%").join("\t")
	          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
	          .replace(/\t=(.*?)%>/g, "',$1,'")
	          .split("\t").join("');")
	          .split("%>").join("p.push('")
	          .split("\r").join("\\'")
	      + "');}return p.join('');");
	   
	    // Provide some basic currying to the user
	    return data ? fn( data ) : fn;
	  };
}


